动态添加Android片段

时间:2014-08-25 14:49:21

标签: android android-fragments

我创建了一个新片段,其中包含另外两个片段:右片段和左片段。我把这个片段称为GridFragment。当我动态添加GridFragments时,只显示最后添加的片段。看起来我每次添加GridFragment实例时都会重复使用它。任何想法为什么会这样?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:weightSum="1.0"><FrameLayout
    android:id="@+id/left_fragment"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:layout_width="0dip">
</FrameLayout>
<FrameLayout
        android:id="@+id/right_fragment"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:layout_width="0dip"
        >
</FrameLayout>

public class GridFragment extends Fragment {
private FragmentManager fm;
private FragmentTransaction ft;
private Fragment leftFragment;
private Fragment rightFragment;

private boolean isLeftFragmentSet = false;
private boolean isRightFragmentSet = false;

public GridFragment(Fragment leftFragment, Fragment rightFragment) {
    this.leftFragment = leftFragment;
    this.rightFragment = rightFragment;
}

public Fragment getLeftFragment() {
    return leftFragment;
}

public Fragment getRightFragment() {
    return rightFragment;
}

public boolean isLeftFragmentSet() {
    return isLeftFragmentSet;
}

public boolean isRightFragmentSet() {
    return isRightFragmentSet;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.grid_fragment, container, false);

    fm = getFragmentManager();

    fm.beginTransaction().add(R.id.left_fragment, leftFragment, leftFragment.toString()).commit();
    fm.beginTransaction().add(R.id.right_fragment, rightFragment, rightFragment.toString()).commit();

    return rootView;
}

public void setLeftFragment(Fragment fragment){
    leftFragment = fragment;
    isLeftFragmentSet = true;
}

public void setRightFragment(Fragment fragment){
    rightFragment = fragment;
    isRightFragmentSet = true;
}
}

我想用它来交替填充宽片段和两个较小片段的屏幕。 这是我想要实现的一个例子:

Grid

1 个答案:

答案 0 :(得分:1)

我在你的代码中看到了根本性的错误。

当您要求rootView正在寻找Activity添加左右片段时,首先FragmentManager不属于R.id.left_fragment布局的一部分在Activity布局内。

其次,如果您想在片段中使用嵌套片段,则必须使用getChildFragmentManager()而不是getFragmentManager()。也可以使用FragmentTransaction链构建器,所以改为:

fm.beginTransaction().add(R.id.left_fragment, leftFragment, leftFragment.toString()).commit();
fm.beginTransaction().add(R.id.right_fragment, rightFragment, rightFragment.toString()).commit();

呼叫:

fm.beginTransaction().add(R.id.left_fragment, leftFragment, leftFragment.toString())
    .add(R.id.right_fragment, rightFragment, rightFragment.toString())
    .commit();

也许您应该考虑将您的片段直接放在Activity布局中,并将GridFragment替换为GridLayout