2013-04-03 145 views
0

如何使用後備按鈕關閉我的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(); 
      } 
     }); 
     } 
} 
+0

如果你指的是保存實例狀態,這應該已經工作。如果您希望在用戶實例回退(或以其他方式結束活動)時保存在EditText中輸入的信息,這取決於底層數據源的內容。一個API?本地存儲? – 2013-04-03 19:13:40

回答

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/