我有一個應用程序。那就是使用Fragments。主要活動以2個片段開始。其中一個片段中包含用於在運行時添加一個3'rd片段像這樣的按鈕:保留在運行時添加的片段
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = getActivity();
if (fragment3 == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment_content3, new ThirdFragment())
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
的ThirdFragment類看起來是這樣的:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(getTag(), "FRAG onCreate CALLED!");
this.setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.third_fragment, container, false);
return view;
的問題是,我無法理解如何在重新創建Activity時保持該片段的視圖不被刪除。我試圖@Override onCreate()方法並使用setRetainInstance(true)無濟於事。
所以,我的問題是:
什麼是正確的做法,以保持一個動態的(在運行時)從當活動被重新被刪除添加片段?