SwitchPreference依赖于其他两个开关首选项

时间:2016-10-13 10:23:41

标签: android sharedpreferences

我的应用中有三个switchpreferences(例如,switch1,switch2和switch3)。我想要实现的是当switch1 AND switch2设置为false时,switch3也必须自动设置为false。如果switch1或switch2中的任何一个设置为true,则switch3也应为true。我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

为switch1和switch2实现onCheckChangedListener,并在onCheckChanged()回调方法中添加以下语句。

switch3.setChecked(switch1.isChecked() || switch2.isChecked())

答案 1 :(得分:0)

按照以下步骤

1)首先创建本地广播接收器

@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-event".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event"));
}

// Inside handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get extra data included in the Intent
    String message = intent.getStringExtra("message");
    Log.e("receiver", "Got message: " + message);
    //perform logic here to store data etc..
  }
};

@Override
protected void onDestroy() {
  // Unregister since the activity is about to be closed.
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

2)编写任何用户定义方法,如下所示:      假设我想在按钮点击事件中调用,

 private void sendMessage() {
  Log.e("sender", "Broadcasting message");
  Intent intent = new Intent("custom-event");
  // You can also include extra data.
  intent.putExtra("message", "Its me !!");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 //Thats it....
}