Android的:不能添加/替换片段
问题描述:
我想一个新片段添加到我的应用程序。结果
但是,这片段是空。
I'm trying to add a new fragment to my app.
But this fragment is null.
我在做什么错了?
片段启动:
ConvertOptions fragment = (ConvertOptions) getSupportFragmentManager()
.findFragmentByTag(Utils.CONVERT_FRAGMENT_TAG);
if (fragment != null)
{
getSupportFragmentManager()
.beginTransaction()
.add(R.id.container, fragment, Utils.CONVERT_FRAGMENT_TAG)
.commit();
}
片段的类code:
Code of Fragment's class:
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" />
答
只要做到这一点:
ConvertOptions mConvertOptions = new ConvertOptions();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, mConvertOptions);
fragmentTransaction.commit();