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

时间:2015-11-02 20:15:15

标签: android android-fragments android-viewpager

我无法以这种方式替换片段:

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;

1 个答案:

答案 0 :(得分:2)

您可以在xml中创建一个片段,然后以编程方式替换它。

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

    public void swapContentFragment(Fragment fragment) {
    
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, fragment, "tagname");
        transaction.addToBackStack("tagname");
        transaction.commitAllowingStateLoss();
    }
    
  2. 使用片段事务更改片段。

    plusOne =
      (+) 1