[英]Is it possible to replace fragments created with layout XML?
我不能這樣替換片段:
A2Fragment a2Fragment = new A2Fragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.fragment_mainLayout, a2Fragment).commit();
第二個片段被添加到第一個片段上。 我嘗試了很多建議的解決方案,但總是一樣。 我現在讀到,不可能替換從布局XML文件添加的片段,應該以編程方式添加它以便可以替換。 這是真的?
我現在在onCreateView中嘗試了此方法並工作了。
Context context = getActivity();
LinearLayout base = new LinearLayout(context);
base.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
base.setLayoutParams(params);
TextView text = new TextView(context);
text.setGravity(Gravity.CENTER);
String title;
text.setText("Pager: ");
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
text.setLayoutParams(params);
FrameLayout layout = new FrameLayout(getActivity());
layout.setId(fragmentId);
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 1;
layout.setLayoutParams(params);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(fragmentId,new A2Fragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
layout.addView(text);
base.addView(layout);
return base;
您可以在xml中創建一個片段,然后以編程方式替換它。
創建XML。 該xml僅包含一個片段。 您可以通過引用其完全限定的類名來使用創建的片段。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:id="@+id/fragment_container" android:layout_centerHorizontal="true" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.yourorg.fragment.EmptyFragment" /> </RelativeLayout>
使用片段事務更改片段。
public void swapContentFragment(Fragment fragment) { FragmentTransaction transaction = mFragmentManager.beginTransaction(); transaction.replace(R.id.fragment_container, fragment, "tagname"); transaction.addToBackStack("tagname"); transaction.commitAllowingStateLoss(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.