Android 交换机兼容性:一旦选中,就会更改
我正在尝试在我的android应用程序中实现一个设置活动,用户可以在其中打开和关闭通知模式。为了实现这一点,我使用Switch Compat。这是布局图。这是我活动布局的一部分Android 交换机兼容性:一旦选中,就会更改,android,material-design,switchcompat,Android,Material Design,Switchcompat,我正在尝试在我的android应用程序中实现一个设置活动,用户可以在其中打开和关闭通知模式。为了实现这一点,我使用Switch Compat。这是布局图。这是我活动布局的一部分 <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal" android:layout_marginStart="2
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_marginStart="24dp"
android:layout_marginTop="90dp"
android:layout_marginEnd="16dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/notifications"
android:layout_gravity="start|center"
android:layout_weight="1"
android:textSize="20sp"
android:textStyle="bold"
android:id="@+id/notifications"/>
<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/notificationsSwitch"
android:layout_gravity="end|center"
android:theme="@style/SwitchTheme"/>
</LinearLayout>
我想做什么
正如我所说,这应该让用户能够打开和关闭通知。
怎么了
代码运行良好,除了一个bug,该bug是当用户想要为ex打开通知,然后改变主意,在他将进入循环的对话框中单击Cancel。
为什么会这样
我已经做了“取消”以这种方式工作,因此如果用户单击“取消”,开关Compat将返回到以前的位置。但因为我有这个状态的方法,所以它触发另一个状态,用户处于循环中。
我试过什么
我尝试使用switch,但无法传递布尔变量b
我还尝试使用flag变量,但找不到逻辑
有人知道我如何克服这一点吗。
提前感谢。当用户单击开关时,OnCheckChanged侦听器被触发一次,然后当您的对话框将其更改回来时,它再次被触发,因此循环。尝试改用OnTouchListener。您可以通过删除OnCheckedChangeListener,然后修改SwitchCompat的状态,然后重新添加OnCheckedChangeListener来解决此问题。这样,当您修改开关时,没有任何内容在侦听 如果您稍微重构一下代码,这将更容易做到。首先,应该将匿名侦听器提取到片段中的变量。换句话说,删除此位:
notificationsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
...
});
并将此添加到onCreateView外部:
现在您已经完成了,可以在onCreateView中设置它,如下所示:
notificationsSwitch = (SwitchCompat) view.findViewById(R.id.notificationsSwitch);
notificationsSwitch.setOnCheckedChangeListener(listener);
notificationsSwitch.setOnCheckedChangeListener(null);
notificationsSwitch.setChecked(true);
notificationsSwitch.setOnCheckedChangeListener(listener);
从这里开始,剩下的就很容易了。进入所有四个积极/消极的听众,让他们看起来像这样:
notificationsSwitch = (SwitchCompat) view.findViewById(R.id.notificationsSwitch);
notificationsSwitch.setOnCheckedChangeListener(listener);
notificationsSwitch.setOnCheckedChangeListener(null);
notificationsSwitch.setChecked(true);
notificationsSwitch.setOnCheckedChangeListener(listener);
您可以使用一个标志作为类属性,当单击对话框中的选项时,该标志将设置为true,如IsFromDialog 然后,在对话框的Onclick函数中,设置 IsFromDialog=true 最后,在课程开始时,你做了什么 如果!b&&!IsFromDialog{ ...
}实现相同功能的最简单方法:
switchWIdget.setOnClickListener{view ->
val switchView = view as SwitchCompat
when (switchView.isChecked) {
false -> {
//do stuff for FALSE
}
true -> {
//do stuff for TRUE
}
}
}
这就是我所做的,加上我添加了一个Runnable,如果我想打开它,它将重置标志。谢谢。