[英]Strange Fragment behavior
我的Activity的onResume()
方法上有以下代碼:
mFragmentManager.popBackStack(FragmentNames.FRAG_MY_CLASS, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction fragTransaction = mFragmentManager.beginTransaction();
fragTransaction.add(R.screenHome.content, MyClass.newInstance(), FragmentNames.FRAG_MY_CLASS);
fragTransaction.commit();
它按預期工作。 我期望的行為是,如果在添加之前將指定的片段從后台彈出。 之所以這樣做,是因為我想每次從上一個活動進入該片段視圖時,或者從下一個活動按回時都重新創建片段視圖。 但是我不明白為什么會這樣,如果我在提交之前沒有這樣做,則會彈出指定的片段:
fragTransaction.addToBackStack(FragmentNames.FRAG_MY_CLASS);
誰知道它為什么起作用? 奇怪的是,我用用來添加指定Fragment的標簽名調用popBackStack。
您沒有直接回答您的問題,而是表示您這樣做是因為
我想每次都重新創建片段視圖
這是一種錯誤的方法。 您應該在其onResume()
重新創建片段的視圖-無需為此進行后退,尤其是當您在
我來自上一個活動
非常適合
您可以繼續在方法onCreate ()
創建片段,該片段控制應根據連接狀態顯示的視圖
public class FragmentA extends Fragment {
boolean flagNetwork;
LinearLayout myContent;
LinearLayout networkError;
@Override
public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState ) {
final View view = inflater.inflate( R.layout.fragment_main, null );
this.myContent = ( LinearLayout ) view.findViewById( R.id.content );
this.networkError = ( LinearLayout ) view.findViewById( R.id.network_unvailable );
if ( this.flagNetwork ) {
this.myContent.setVisibility( View.VISIBLE );
} else {
this.networkError.setVisibility( View.VISIBLE );
}
return view;
}
}
//布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:visibility="gone" >
</LinearLayout>
<LinearLayout
android:id="@+id/network_unvailable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:visibility="gone" >
<!-- your hadler to error -->
</LinearLayout>
</RelativeLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.