zoukankan      html  css  js  c++  java
  • Android笔记之Activity的生命周期

    1.   onCreate, onStart, onResume, onPause, onStop, onRestart, onDestroy

    如果连这7个方法都不清楚的话,那么就该从头开始看Android了。下图是Activity的生命周期,加深记忆用:

    2、 onSaveInstanceState与onRestoreInstanceState

    当设备的配置(横竖屏、语言等)发生变化而使Activity自动重启,或者Activity从前台转到后台(如,按下Home键)的时 候,Activity会调用onSaveInstanceState(Bundle)方法将当前Activity的状态保存到一个Bundle变量中。这 个Bundle变量与onCreate(Bundle)方法和onRestoreInstanceState(Bundle)中的Bundle参数是同一 个,也就是说,后两个方法通过传入的Bundle参数还原Activity的状态。

    不过,虽然Activity的状态保存到了Bundle中,但是这些状态数据却无法从Bundle中取出。要想手动地设置一些重启后需要的状态数据,可以直接调用该Bundle实例的putXXX方法存入额外的数据信息。

    如下列所示:

    public class SaveNRestoreInstanceStateActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.save_restore_state);
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            EditText et1 = (EditText) findViewById(R.id.et1);
            EditText et2 = (EditText) findViewById(R.id.et2);
            
            et1.setText("This is et1");
            et2.setText("This is et2");
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            outState.putString("et1", "This is from outState and this is et1");
            outState.putString("et2", "This is from outState and this is et2");
            
            super.onSaveInstanceState(outState);
        }
    
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            
            EditText et1 = (EditText) findViewById(R.id.et1);
            EditText et2 = (EditText) findViewById(R.id.et2);
            
            et1.setText(savedInstanceState.getString("et1"));
            et2.setText(savedInstanceState.getString("et2"));
        }
    
    }

    3.   onBackPressed

    回退键的处理方法,一般用来屏蔽回退键或者在添加后退时的额外功能(弹出确认退出的对话框等)。

    原文:http://blog.csdn.net/sadfishsc/article/details/7345738

  • 相关阅读:
    Project Euler Problem 26-Reciprocal cycles
    Project Euler Problem 24-Lexicographic permutations
    Project Euler Problem 23-Non-abundant sums
    AtCoder Beginner Contest 077 D Small Multiple(最短路)
    浮点数表示及其实现
    ACM water
    Makefile经典教程(掌握这些足够)
    Linux makefile 教程 非常详细,且易懂
    C/C++中const的用法 分类: C/C++ 2015-07-05 00:43 85人阅读 评论(0) 收藏
    自动化测试工具QTP的使用实例 分类: 软件测试 2015-06-17 00:23 185人阅读 评论(0) 收藏
  • 原文地址:https://www.cnblogs.com/xingyyy/p/3280022.html
Copyright © 2011-2022 走看看