在 xml 布局文件中声明 fragment 的标准方法是
<LinearLayout ...>
<fragment class="com.example.SomeFragment"
</LinearLayout>
其中 SomeFragment 是一个类似定义的 java 类
class SomeFragment extends Fragment {
...
}
可以说,我有 3 个 fragment ; fragment 1、 fragment 2 和 fragment 3。当用户启动应用程序时,我向他们展示 fragment1,当他们点击一个按钮时,我将 fragment1 替换为 fragment2,等等。
在单个布局 xml 文件中定义 3 个 fragment 的最佳方法是什么?
最佳答案
您应该为此使用 FrameLayout,这样您就不必在 XML 中指定 fragment 类,并且它不限于一个类。
<FrameLayout
android:id="@+id/contentFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
你可以像这样在代码中设置 fragment
Fragment fragment = new YourFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();
关于android - 在 fragment View 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793576/