標籤:android開發
我近期學習了一下android sdk,不太清楚裡面的一些原理,如何儲存應用程式的狀態,看下面hello的小例子:
| 12345678910111213141516171819202122232425 |
package com.android.hello;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extendsActivity {/** Called when the activity is first created. */@Overridepublicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mTextView =new TextView(this);if(savedInstanceState == null) {mTextView.setText("Welcome to HelloAndroid!");}else {mTextView.setText("Welcome back.");}setContentView(mTextView);}privateTextView mTextView = null;} |
這個android 小例子應該是每個人都開發過的,我每次關閉程式再開啟是都是給我顯示第一個Welcome to HelloAndroid ,我想在第二次訪問的時候能夠顯示 Welcome back,我該如何處理?
處理方法
你需要重寫 onSaveInstanceState(Bundle savedInstanceState),把你想要儲存的狀態寫入到 Bundle 中,如下
| 123456789101112 |
@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) {super.onSaveInstanceState(savedInstanceState);// Save UI state changes to the savedInstanceState.// This bundle will be passed to onCreate if the process is// killed and restarted.savedInstanceState.putBoolean("MyBoolean",true);savedInstanceState.putDouble("myDouble",1.9);savedInstanceState.putInt("MyInt",1);savedInstanceState.putString("MyString","Welcome back to Android");// etc.} |
Bundle 的本質是鍵值對的方式儲存,你可以通過 onCreate()和 onRestoreInstanceState() 或的對應的值
| 12345678910 |
@Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);// Restore UI state from the savedInstanceState.// This bundle has also been passed to onCreate.booleanmyBoolean = savedInstanceState.getBoolean("MyBoolean");doublemyDouble = savedInstanceState.getDouble("myDouble");intmyInt = savedInstanceState.getInt("MyInt");String myString = savedInstanceState.getString("MyString");} |
您通常會使用這項技術來儲存執行個體的值的應用程式(選擇,未儲存的文本等)。
原文地址:http://www.itmmd.com/201410/38.html
該文章由 萌萌的IT人 整理髮布,轉載須標明出處。
Android 報錯 Activity 狀態