是否可以替换使用布局 XML 创建的片段?

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 中创建片段,然后以编程方式替换它。

  1. 创建 XML。这个 xml 只包含一个片段。您可以通过引用其完全限定的 class 名称来使用您创建的片段。

    <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>
    
  2. 使用片段事务来改变你的片段。

    public void swapContentFragment(Fragment fragment) {
    
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, fragment, "tagname");
        transaction.addToBackStack("tagname");
        transaction.commitAllowingStateLoss();
    }