Java 如何检索共享首选项的值以检查条件
这里我有三个按钮是否可能对于三个按钮,我在按钮点击时更改了颜色,并将点击按钮的值存储在共享首选项中,以便在我返回按钮时保持颜色 @凌驾 公共视图getView(最终整数位置、视图转换视图、视图组父视图){Java 如何检索共享首选项的值以检查条件,java,android,Java,Android,这里我有三个按钮是否可能对于三个按钮,我在按钮点击时更改了颜色,并将点击按钮的值存储在共享首选项中,以便在我返回按钮时保持颜色 @凌驾 公共视图getView(最终整数位置、视图转换视图、视图组父视图){ SharedReferences使您能够存储不同类型的数据,例如boolean或int 要完成任务,您可以将每个按钮的颜色存储在SharedReferences中;类似于: editor.putInt("button_one", R.color.buttone_one_selected);
SharedReferences
使您能够存储不同类型的数据,例如boolean
或int
要完成任务,您可以将每个按钮的颜色存储在SharedReferences
中;类似于:
editor.putInt("button_one", R.color.buttone_one_selected);
请记住,在检索该颜色时,必须使用以下方法进行解析:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
您可以使用此更改按钮的颜色 在onCreate中:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
现在检查存储在首选项中的布尔值:
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
现在,在按钮的onClick方法中:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}
试一试,你想在你的首选项中存储按钮的颜色吗?是的,如果我已经选择了按钮,我将永远保持按钮的颜色我想为每个按钮创建变量,如果条件你使用了多少个按钮?所有按钮的状态如何?每个按钮的状态相同还是不同所有状态相同或相互关联您可以使用一个if-else语句并对所有按钮执行颜色更改…这里我使用了3个按钮。我使用了此方法,但首先我单击了yes按钮,它的颜色更改,然后我单击了no按钮,yes按钮应恢复正常,现在no按钮的颜色应在此处更改when我单击了另一个按钮,第一个按钮保持颜色在每个按钮的onClick()方法上更改颜色,然后…像“是”按钮颜色一样,将“是”按钮的颜色设置为“选定”,将其他按钮的颜色设置为“正常”…并执行相同的“否”和“可能”按钮。。。。
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}