Fragment的简单用法

创建碎片

先新建一个碎片的布局example_fragment.xml,然后再创建自己的fragment 类ExampleFragment 继承自Fragment,并重写其中的onCreateView() 方法:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

inflate() 方法将xml资源转化为view 对象并返回。它接收三个参数:

  • 需要加载的布局文件的ID;
  • 一个ViewGroup 作为加载布局的父对象。这里传入onCreateView() 的参数container 就可以;
  • 第三个参数是一个布尔值,如果传入true的话,将会连同父对象一起被返回。


将碎片添加到Activity

添加碎片的方法有静态添加和动态添加两种

1. 静态添加

这种方法直接在Activity 的布局文件中声明Fragment,例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

name 属性指定碎片布局所对应的类。

2. 动态添加

在Activity 中添加、替换、删除等一系列操作称作一项“事务”。要开启一项事务,需要一个FragmentTransaction 对象。获得FragmentTransaction 对象的方法如下:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然后就可以调用add() 方法添加碎片了:

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

可以同时进行多项操作,在操作完毕以后用commit() 方法提交。


为碎片添加返回栈

如果想要点击返回键的时候返回到上一个状态,需要为事务添加返回栈,在commit() 之前调用addToBackStack() 方法即可:

			transaction.addToBackStack(null);

碎片与活动的通信

碎片与活动的通信,说白了也就是相互调用对方的方法。其实也就是只需要获取对方对象的实例就可以了。

碎片可以通过getActivity() 方法获取Activity 的实例,例如获取Activity 的Layout 中的View 对象:

View listView = getActivity().findViewById(R.id.list);

同样的,在Activity 中你也可以借助FragmentManager 对象的findFragmentById() 或者findFragmentByTag() 方法来获取Fragment 实例:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

后面还会详细说到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值