我正在制作一个项目,其中我使用两个切换按钮,我必须保存状态,以便它可以在后台工作,因为它是保存与否。我能够保存第一个togglebutton的状态,但不能保存第二个togglebutton的状态,第二个也可以按照启动和停止服务。所以任何人都可以告诉我必须做什么,以便我可以保存togglebuttons的状态
公共类MainActivity扩展了AppCompatActivity {
public ToggleButton led1, led2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
led1 = (ToggleButton) findViewById(R.id.toogleButton1);
led2 = (ToggleButton) findViewById(R.id.toogleButton2);
SharedPreferences sharedPrefs = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
led1.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
SharedPreferences sharedPrefs1 = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
led2.setChecked(sharedPrefs1.getBoolean("NameOfThingToSave", true));
}
public void clickHendler(View v) throws InterruptedException {
switch (v.getId()) {
case R.id.toogleButton1:
if (led1.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.togglebutton", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.togglebutton", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
break;
case R.id.toogleButton2:
if (led2.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
break;
}
}
答案 0 :(得分:0)
您不能只使用相同的密钥来存储两个切换按钮的值。这样做:
public ToggleButton led1, led2;
public SharedPreferences sharedPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
led1 = (ToggleButton) findViewById(R.id.toogleButton1);
led2 = (ToggleButton) findViewById(R.id.toogleButton2);
sharedPrefs = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
led1.setChecked(sharedPrefs.getBoolean("Button_one_value", true));
led2.setChecked(sharedPrefs.getBoolean("Button_two_value", true));
}
public void clickHendler(View v) throws InterruptedException {
SharedPreferences.Editor editor = sharedPrefs.edit();
switch (v.getId()) {
case R.id.toogleButton1:
if (led1.isChecked()) {
editor.putBoolean("Button_one_value", true);
} else {
editor.putBoolean("Button_one_value", false);
}
editor.commit();
break;
case R.id.toogleButton2:
if (led2.isChecked()) {
editor.putBoolean("Button_two_value", true);
} else {
editor.putBoolean("Button_two_value", false);
}
editor.commit();
break;
}
}