onsavedinstance(Bundle savedinstancestate)方法的触发时机,其典型的情景是按home键或者切换activity,这样的activity可能被销毁的场合,但是按back键退出程序,则不会调用此方法,适合保存一些非持久性的数据(即程序运行期间需要储存的数据)。
而onpause(),不管是可能销毁还是退出程序,都必须调用,适合保存持久性的数据,但是android本身没有为此方法提供bundle参数,因此我们可以选用做一个静态变量或者是提供一个sharedpreference作为数据载体。
我练习的时候,使用了一个静态变量保存数据,改变数据以后,重新启动程序,改变的数据得到了保存,看代码:
public class MainActivity extends Activity { private ListView namesListView; private MyAdapter adapter; private ArrayList<String> names; private static Bundle outState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("create", String.valueOf(savedInstanceState == null)); if (outState != null) { names = outState.getStringArrayList("names"); } else { names = new ArrayList<String>(); names.add("小李"); names.add("小刚"); names.add("小明"); names.add("小花"); names.add("小红"); names.add("小兰"); } namesListView = (ListView) findViewById(R.id.nameList); adapter = new MyAdapter(this, names); namesListView.setAdapter(adapter); } private void singleRefresh(int id){ if (namesListView != null) { int start = namesListView.getFirstVisiblePosition(); int end = namesListView.getLastVisiblePosition(); for (int i = start; i < end; i++) { if (id == namesListView.getItemIdAtPosition(i)) { TextView view = (TextView) namesListView.getChildAt(i-start); names.set(i, "我变身超级赛亚人啦!"); adapter.getView(i, view, null); break; } } } } public void refresh(View v){ singleRefresh(0); } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); //outState.putStringArrayList("names", names); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if (outState != null) { outState.clear(); outState = null; } outState = new Bundle(); outState.putStringArrayList("names", names); } }
时间: 2024-10-26 02:47:00