3

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

这是我的Activity代码:

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();
            }
        });
        }
}
4

1 回答 1

3

您将不得不实现 onSavedInstanceState() 并使用您正在显示的视图的 int 填充它。

然后,在您的 onCreate(Bundle savedInstanceState) 方法中,您将从包中挖掘 int 并将您的内容视图设置为该值。

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/

于 2013-04-03T22:42:47.633 回答