【发布时间】:2016-12-26 22:30:45
【问题描述】:
我能够使用共享首选项来存储复选框的值,但我无法保存它应该执行的 动作。我需要的动作是选中复选框时应该显示一个按钮,如果未选中复选框,则不应显示按钮(隐藏/显示按钮在不同的活动中完成)。所以我所做的是我在 if/else 条件下传递了值 isCheckedValue = isChecked;
final CheckBox checkBox = (CheckBox) findViewById(R.id.add_fb);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
checkBox.setChecked(preferences.getBoolean("checked",false));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
editor.putBoolean("checked", isChecked);
editor.apply();
if(checkBox.isChecked()) {
isCheckedValue = isChecked;
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
});
如果检查了 chkbox,则值将使用 onBubbleClick 中的意图传递,使用布尔传递数据 in.putExtra("yourBoolName", isCheckedValue ); 您可以在下面的代码中注意到它
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
@Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
@Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
它是如何工作的:一开始按钮在单击复选框之前不会显示,一旦选中复选框,按钮就会显示,即使取消选中复选框也不会隐藏。
它的工作原理如果复选框被选中,按钮应该显示,如果复选框未被选中,按钮应该隐藏。
【问题讨论】:
-
尝试使用
.commit()而不是.apply(),我相信.commit是同步的,而另一个在后台运行。 -
@CookieMonster 无论如何都没有用。
标签: java android android-studio checkbox sharedpreferences