A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 瀚海狼烟 中级黑马   /  2015-3-21 20:37  /  1072 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

提供Fragment的UI,必须实现onCreateView()方法。

  假设Fragment的布局设置写在example_fragment.xml资源文件中,那么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);
    }
}
复制代码


  onCreateView()中container参数代表该Fragment在Activity中的父控件;savedInstanceState提供了上一个实例的数据。

  inflate()方法的三个参数:

  第一个是resource ID,指明了当前的Fragment对应的资源文件;

  第二个参数是父容器控件;

  第三个布尔值参数表明是否连接该布局和其父容器控件,在这里的情况设置为false,因为系统已经插入了这个布局到父控件,设置为true将会产生多余的一个View Group。


把Fragment加入Activity
  当Fragment被加入Activity中时,它会处在对应的View Group中。

  Fragment有两种加载方式:一种是在Activity的layout中使用标签<fragment>声明;另一种方法是在代码中把它加入到一个指定的ViewGroup中。

  另外,Fragment它可以并不是Activity布局中的任何一部分,它可以是一个不可见的部分。这部分内容先略过。



加载方式1:通过Activity的布局文件将Fragment加入Activity

  在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>
复制代码


  其中android:name属性填上你自己创建的fragment的完整类名。

  当系统创建这个Activity的布局文件时,系统会实例化每一个fragment,并且调用它们的onCreateView()方法,来获得相应fragment的布局,并将返回值插入fragment标签所在的地方。

  有三种方法为Fragment提供ID:

  android:id属性:唯一的id

  android:tag属性:唯一的字符串

  如果上面两个都没提供,系统使用容器view的ID。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马