android橫豎屏切換與數據保存

一,橫豎屏切換時不重新載入數據,隻需在menifest中加入:

android:configChanges="keyboardHidden|orientation"

二,橫豎屏切換時重新載入數據,程序會程序進入onCreate,因此需要對數據進行存儲以備後用。

***方法一:

    @Override
    public Object onRetainNonConfigurationInstance() {

        // save data :browserHistoryAdapter
        Intent i = new Intent();
        Bundle b = new Bundle();
        b.putSerializable(KEY_HISTORY_SAVED, (Serializable) browserHistoryAdapter);
        i.putExtras(b);
        return i;
    }

        // get saved data after configure changed :browserHistoryAdapter
        Intent historySaved;
        if((historySaved = (Intent) getLastNonConfigurationInstance()) == null){
            historySaved = getIntent();
        }
       
        if(historySaved != null && historySaved.getExtras() != null){
            browserHistoryAdapter = (BrowserHistoryAdapter) historySaved.getExtras().get(KEY_HISTORY_SAVED);
        }
***方法二:

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

        // save data :url
        outState.putString(STR_URL, url);
    }

        // get saved data after configure changed :url
        if (savedInstanceState != null) {
            url = savedInstanceState.getString(STR_URL);
        }

 

摘自 fhy_2008的專欄

發佈留言