![](/img/trans.png)
[英]How to retain state of views of orientation changes in Android Conductor?
[英]how to retain state of listview during orientation changes?
大家好,我知道閱讀我的問題的標題后,您會發現答案很簡單,但是由於我是android開發的新手,所以我發現很難在方向更改期間保持listview的狀態,甚至碎片狀態也很難在Google上沖浪但是我找不到方向改變期間保持狀態的令人滿意的解決方案,我知道它們是一個onsaveinstancestate()方法,您必須在其中放置每個視圖數據,但是我認為它們是更好的解決方案,因此請幫助我為它。您還可以提供有關方向更改的優秀教程的鏈接。
我注意到,根據您的實現,默認情況下會保存listview狀態,但要恢復該狀態,請重新創建listview並確保隨后(而不是之前)調用具有savedInstanceState
作為參數的超級方法之一。 為什么? 由於已保存列表視圖狀態,因此super方法將其還原,並且如果在調用super之后重新創建,則將覆蓋已還原狀態。
另一種方法是覆蓋活動的onSaveInstanceState(outState)
,將listview狀態放入包中,
outState.putParcelable("listview.state", listview.onSaveInstanceState());
然后,當您重寫onRestoreInstanceState(savedInstanceState)
,在重新創建列表視圖之后,您調用;
Parcelable listViewState = savedInstanceState.getParcelable("listview.state"); listview.onRestoreInstanceState(listViewState);
檢查空值並祝您好運!
您可以使用setRetainInstance(true); 零碎地
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// find the retained fragment on activity restarts
FragmentManager fm = getFragmentManager();
dataFragment = (RetainedFragment) fm.findFragmentByTag(“data”);
// create the fragment and data the first time
if (dataFragment == null) {
// add the fragment
dataFragment = new DataFragment();
fm.beginTransaction().add(dataFragment, “data”).commit();
// load the data from the web
}
// the data is available in dataFragment.getData()
...
}
}
在片段內創建Listview-片段將是-
public class RetainedFragment extends Fragment {
// this method is only called once for this fragment
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
// retain this fragment
setRetainInstance(true);
// create your listview here
}
}
通過將以下行添加到清單中,作為Activity標簽內的一個屬性,我將保留整個Activity的狀態:
android:configChanges="keyboardHidden|orientation|screenSize"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.