我有一个switch按钮(实际上是一个自定义按钮),我想出于某种原因禁用滑动功能; 我希望用户只能点击它.有没有办法实现这个目标?谢谢.
小智 42
您可以将setClickable(false)设置为Switch,然后在Switch的父级中侦听onClick()事件并以编程方式切换它.该开关仍将显示为启用但不会进行滑动动画.
...
[在onCreate()]
Switch switchInternet = (Switch) findViewById(R.id.switch_internet);
switchInternet.setClickable(false);
Run Code Online (Sandbox Code Playgroud)
...
[点击听众]
public void ParentLayoutClicked(View v){
Switch switchInternet = (Switch) findViewById(R.id.switch_internet);
if (switchInternet.isChecked()) {
switchInternet.setChecked(false);
} else {
switchInternet.setChecked(true);
}
}
Run Code Online (Sandbox Code Playgroud)
...
[layout.xml]
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="ParentLayoutClicked"
android:focusable="false"
android:orientation="horizontal" >
<Switch
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:id="@+id/switch_internet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="NOT CONNECTED"
android:textOn="CONNECTED"
android:focusable="false"
android:layout_alignParentRight="true"
android:text="@string/s_internet_status" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
adv*_*ait 19
更好的方法是阻止Switch类接收MotionEvent.ACTION_MOVE事件.
这可以通过以下方式完成:
switchButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return event.getActionMasked() == MotionEvent.ACTION_MOVE;
}
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据需要在交换机上自由设置单击侦听器.
要禁用Switch,请使用以下方法
switchBtn.setEnabled(false);
Run Code Online (Sandbox Code Playgroud)
要使开关不可点击使用
switchBtn.setClickable(false);
Run Code Online (Sandbox Code Playgroud)
其中switchBtn是Switch对象
我的解决方案是:
switchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
//Your code
}
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
或者黄油刀:
@OnTouch(R.id.switchView)
public boolean switchStatus(Switch switchView, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// your code
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33319 次 |
| 最近记录: |