保存Android的活动状态

时间:2015-04-29 10:15:38

标签: android savestate

当我再次开始活动时,如果句子保持更改,如何保存setBackgroundResource和setTextColor的活动状态?

if (cases == 1) {
            TextView layout = (TextView) findViewById(R.id.textView1);
            layout.setBackgroundResource(R.drawable.izbrano);
            layout.setTextColor(Color.parseColor("#d7a308"));
            ImageView image = (ImageView) findViewById(R.id.imageOdprto);
            image.setImageResource(R.drawable.o1);
            String strIi = formatter.format(cases);
            text.setText(strIi + "€");

            }

3 个答案:

答案 0 :(得分:0)

您似乎需要存储设置而不是Activity的状态。在这种情况下,我建议使用SharedPreferences

答案 1 :(得分:0)

也许只记住你的案例值(假设它是全局的)就更容易了:

@Override
public void onPause(){
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("cases", cases);
    editor.commit();
    super.onPause();
}

@Override
public void onResume(){
    super.onResume();
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    cases = sharedPref.getInt("cases", 0);  
    if ( cases == 0 ){
        // do stuff
    } else {
        // do more stuff
    }
}

答案 2 :(得分:0)

使用偏好不是更优选的。 这是一个很好的教程,如何保存活动状态。请检查此Link

它表明,

int someVar;
@Override
protected void onSaveInstanceState(Bundle outState) {
   outState.putInt("someVar", someVar);
   outState.putString(“text”, tv1.getText().toString());
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   someVar = savedInstanceState.getInt("someVar", 0);
   tv1.setText(savedInstanceState.getString(“text”));
}