在片段视图之间切换 [英] Switching between Fragment view

查看:30
本文介绍了在片段视图之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在xml布局文件中声明片段的标准方法是

The standard way to declare fragments in a xml layout file is

<LinearLayout ...> 
    <fragment class="com.example.SomeFragment"
</LinearLayout>

其中 SomeFragment 是一个像

where SomeFragment is a java class defined like

class SomeFragment extends Fragment { 
    ... 
}

比方说,我有 3 个片段;片段 1、片段 2 和片段 3.当用户启动应用程序时,我向他们展示 fragment1,当他们点击按钮时,我将 fragment1 替换为 fragment2,等等.

Lets say, I have 3 fragments; fragment1, fragment2, and fragment3. When the user launches the app, I show them fragment1, and when they click on a button, I replace the fragment1 with fragment2, etc.

在单个布局 xml 文件中定义 3 个片段的最佳方法是什么?

What is the best approach to define the 3 fragments in a single layout xml file?

推荐答案

你应该为此使用 FrameLayout,这样你就不必在 XML 中指定片段类,这样它就不仅限于一个类.

You should use a FrameLayout for that, that way you don't have to specify the fragment class in the XML and that way it is not limited to one class.

<FrameLayout 
    android:id="@+id/contentFragment"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" />

然后你可以像这样在代码中设置片段

and than you can set the fragment in the code like this

Fragment fragment = new YourFragment();

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();

这篇关于在片段视图之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆