Android:无法添加/替换片段

时间:2015-03-25 08:50:37

标签: java android android-fragments

我正在尝试向我的应用添加新片段 但是这个片段是空的。

我做错了什么?

片段发布:

ConvertOptions fragment = (ConvertOptions) getSupportFragmentManager()
                    .findFragmentByTag(Utils.CONVERT_FRAGMENT_TAG);

            if (fragment != null)
            {
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.container, fragment, Utils.CONVERT_FRAGMENT_TAG)
                        .commit();
            }

片段代码类:

    public class ConvertOptions extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.convert_options_fragment, null);

        return view;
    }
}

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/options_convert_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button2"
    android:layout_gravity="center_horizontal" />

2 个答案:

答案 0 :(得分:2)

//首先初始化新片段

 ConvertOptions fragment = new ConvertOptions();

        if (fragment != null)
        {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, fragment, Utils.CONVERT_FRAGMENT_TAG)
                    .commit();
        }

答案 1 :(得分:2)

这样做:

ConvertOptions mConvertOptions = new ConvertOptions();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, mConvertOptions);
fragmentTransaction.commit();