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

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

问题描述

本标准的方式在一个XML布局文件中声明片段是

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

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

在这里SomeFragment是一个Java类中定义的如

where SomeFragment is a java class defined like

class SomeFragment extends Fragment { 
    ... 
}

可以说,我有3个片段;片段1,fragment2和fragment3。当用户启动应用程序,我向他们展示片段1,当他们点击一个按钮,我替换fragment2的片段1等。

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

和比你可以在code是这样设置的片段

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天全站免登陆