Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off". So can any budy tell mw what should i have to save the state of the toogleButton selection and perform som开发者_开发知识库e action based on that toggleButton selection state. . . Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck
精彩评论