2017-04-23 73 views
-2

我想在返回此活動後將數據保存在編輯文本的活動中。怎麼做?我應該使用OnPauseOnResume返回後在活動中保存數據

+0

使用saveinstancestate在活動之間切換時保留數據 –

+2

[使用保存實例狀態保存Android活動狀態]的可能重複(http://stackoverflow.com/questions/151777/saving-android-activity-state-using-save -instance-state) – lnman

+0

這個問題有點不清楚。請更具體一些。 –

回答

0

您可以使用Bundle savedInstanceState保存應用程序的狀態。 當我們改變設備的方向時,數據就會丟失。

在下面的例子,我們保存價值

int value = 1;  

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 

    /* EditText editText = 
      (EditText) findViewById(R.id.editText); 
    CharSequence text = editText.getText();// getting text in edit text 
    outState.putCharSequence("savedText", text);// saved text in bundle object (outState) 
    */ 

    outState.putInt("value", value); 

} 

@Override 
protected void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 

    /* CharSequence savedText=savedInstanceState.getCharSequence("savedText"); 
    Toast.makeText(this, ""+savedText, Toast.LENGTH_SHORT).show();*/ 

    value = savedInstanceState.getInt("value"); 
    Toast.makeText(this, ""+value, Toast.LENGTH_SHORT).show(); 
} 

public void buttonClicked(View view) { 
    value++; 
} 

XML佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:inputType="text" 
     android:id="@+id/editText"/> 
    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:inputType="text"/> 
<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Click Me" 
    android:onClick="buttonClicked"/> 

</LinearLayout> 

注:在編輯文本的任何信息,按鈕等 會自動由Android,只要你指定要堅持一個ID。 所以第二個編輯文本將會清除它的信息,但是如果你旋轉上面例子中的屏幕,不能編輯帶有第一編輯文本的編輯文本。

相關問題