当用户终止应用程序或重新启动时,我需要保存有关切换按钮的信息我想显示按钮的先前状态谢谢
public class MainActivity extends ActionBarActivity {
ToggleButton toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.app.ActionBar menu = getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setLogo(R.mipmap.ic_launcher);
menu.setDisplayUseLogoEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
enableNotifications();
} else {
makeDialog();
}
}
});
}
答案 0 :(得分:0)
使用共享偏好。
togButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int notification_status = Integer.parseInt(mPreferences.getString("status", "-1"));
SharedPreferences.Editor editor=mPreferences.edit();
Log.i("notification_status="+notification_status,"888");
if(notification_status==-1){
editor.putString("status", "1");
holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
//do your stuff
}else if(notification_status==1){
editor.putString("status", "0");
holder.notification_btn.setBackgroundResource(R.drawable.notification_off);
//do your stuff
}else if(notification_status==0){
editor.putString("status", "1");
holder.notification_btn.setBackgroundResource(R.drawable.notification_on);
//do your stuff
}
editor.commit();
}
});
答案 1 :(得分:0)
使用共享首选项作为以下类
public class YourPreferenes {
private Context mContext;
private SharedPreferences mPrefs;
private static YourPreferenes mYourPreferenes;
private YourPreferenes(Context ctx){
mContext = ctx;
mPrefs = mContext.getSharedPreferences("ATSPreferenes", Context.MODE_PRIVATE);
}
public static ATSPreferenes getInstance(Context ctx){
if(mYourPreferenes == null){
mYourPreferenes = new YourPreferenes(ctx);
}
return mYourPreferenes;
}
public void setButtonState(boolean btnstate){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("btnstate", btnstate);
editor.commit();
}
public boolean getButtonState(){
return mPrefs.getBoolean("btnstate", false);
}
}
And get your saved togalbutton stat even you kill your app.