android - 在 fragment View 之间切换

标签 android android-layout android-fragments

在 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/

相关文章:

java - 如何访问 Dialog Builder 内部类中的数据?

android - 如何解决Unity "Gradle build failed"?

android - 如何将搜索添加到操作栏?

android - 在 Recycler View 中使用水平线性布局管理器时布局元素的对齐方式发生变化

java - 具有多个适配器和 View 类型的 Recycler View 不工作

java - 在其 ViewPager 中使用带有 ScrollView 的 fragment 隐藏选项卡式 Activity 中的工具栏

android - 如何在 Visual Studio for Mac for Xamarin 中添加更多 Android 模拟器设备?

android - Android 移动设备上的 RTP 客户端应用程序

Android - 3 次滑动后 Sherlock 内容消失

android - 恢复 Activity 时 FragmentManager 中的 IndexOutOfBoundsException