按下后退按钮时保存状态 [英] save the state when back button is pressed

查看:113
本文介绍了按下后退按钮时保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序.如果按后退按钮,应保存应用程序的状态.如何保存与所有这些onPause()onResume()onRestoresavedInstance()混淆的状态..am?我应该使用其中哪几个来保存应用程序的状态?例如,当我按下退出按钮时,我的整个应用程序应该退出,我已经使用了finish()吗?

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?

   public void onCreate(Bundle savedInstanceState)
   {   

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    s1=(Button)findViewById(R.id.sn1);
    s1.setOnClickListener(this);
    LoadPreferences();
    s1.setEnabled(false);
    }

    public void SavePreferences()
 {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("state", s1.isEnabled());
       }
 public void LoadPreferences()
 {
     System.out.println("LoadPrefe");
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        Boolean  state = sharedPreferences.getBoolean("state", false);
        s1.setEnabled(state);
       }
 @Override
 public void onBackPressed()
 {
    System.out.println("backbutton");
    SavePreferences();
     super.onBackPressed();
 }

推荐答案

您需要做的是,而不是使用KeyCode Back,而是在Activity中覆盖了以下方法,

What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,

@Override
public void onBackPressed() {

    super.onBackPressed();
}

并使用 SharedPrefrence 保存按钮的状态,下次输入活动"时,从 Sharedpreference 中获取值并相应地设置按钮的启用状态

And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.

示例

private void SavePreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("state", button.isEnabled());
    editor.commit();   // I missed to save the data to preference here,. 
   }

   private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    Boolean  state = sharedPreferences.getBoolean("state", false);
    button.setEnabled(state);
   }

   @Override
public void onBackPressed() {
    SavePreferences();
    super.onBackPressed();
}

onCreate(Bundle savedInstanceState)
{
   //just a rough sketch of where you should load the data
    LoadPreferences();
}

这篇关于按下后退按钮时保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆