关于android:如何保存我的活动状态?

How do I save the state of my activity?

本问题已经有最佳答案,请猛点这里访问。

如何保存我的Activity的方式,当用后退按钮关闭并恢复时,与关闭时的方式相同。

这是我的Activity代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Levels extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
        setContentView(R.layout.levels);

        final EditText anstext1 = (EditText) findViewById(R.id.anstext1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {  
                 String result = anstext1.getText().toString();
                 if(result.equals("they"))
                     setContentView(R.layout.social);
                 else
                   Toast.makeText(getApplicationContext(),"Wrong", Toast.LENGTH_LONG).show();
            }
        });
        }
}


您必须实现onSavedinstanceState(),并用要显示的视图的int填充它。

然后,在onCreate(bundle savedinstancestate)方法中,您将从bundle中挖掘int,并将内容视图设置为它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class yourActivity extends Activity {

    private static final String KEY_STATE_VIEW_ID ="view_id";
    private int _viewId = R.layout.levels;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_STATE_VIEW_ID) {
                _viewId = savedInstanceState.getInt(KEY_STATE_VIEW_ID);
            }
        }
        setContentView(_viewId);
        // in your onClick set viewId to R.layout.social
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt(KEY_STATE_VIEW_ID, _viewId);
    }
}

例如:http://www.how-to-develop-android-apps.com/tag/onsaveinstancestate/