当前位置:   article > 正文

Activity重新创建之recreate_android recreate

android recreate

Android在3.0之后,Activity引入了新的一个方法:recreate(),从字面意思就知道是重新创建Activity的,3.0+版本才可以使用。

/**
 * 调用recreate方法重新创建Activity会比正常启动Activity多调用了onSaveInstanceState
 * ()和onRestoreInstanceState()两个方法,onSaveInstanceState()会在onCreate方法之前调用。
 * 所以可以在onCreate()方法中获取onSaveInstanceState()保存的Theme数据
 * 
 * @description:
 * @author ldm
 * @date 2016-4-19 上午9:34:49
 */
public class MainActivity extends Activity implements OnClickListener {
    private Button recreate;
    private int mCurrentTheme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 从onSaveInstanceState(Bundle outState)方法中保存的数据取出Theme
        if (savedInstanceState != null) {
            mCurrentTheme = savedInstanceState.getInt("mCurrentTheme");
            // 切换Activity的Theme
            switch (mCurrentTheme) {
            case android.R.style.Theme_Holo_Light:
                mCurrentTheme = android.R.style.Theme_Holo_Dialog;
                break;
            case android.R.style.Theme_Holo_Dialog:
                mCurrentTheme = android.R.style.Theme_Holo;
                break;
            default:
                mCurrentTheme = android.R.style.Theme_Holo_Light;
                break;
            }
            setTheme(mCurrentTheme);
        }

        setContentView(R.layout.activity_main);
        this.recreate = (Button) findViewById(R.id.recreate);
        this.recreate.setOnClickListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("mCurrentTheme", mCurrentTheme);// 把当前Theme保存
    }

    @Override
    public void onClick(View v) {
        recreate();// 直接调用Activity的recreate()方法重启Activity
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/898768
推荐阅读
相关标签
  

闽ICP备14008679号