Fragment的静态加载

假如我们要实现一个如图所示左边占1/3右边占2/3的一个效果


这个时候就需要用到Fragment

由图可见,最少需要两个布局文件

即左碎片(left_fragment.xml)和右碎片(right_fragment.xml)

left_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent">
    <Button
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:text="This is button in left_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

right_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary">
    <TextView
        android:id="@+id/textview"
        android:layout_gravity="center_horizontal"
        android:text="This is textview in left_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

可以看出,左边仅有一个按钮,右边是一个文本框

目录里提到,Fragment和Activity很像,那么有布局文件也应该有Class文件

我们 New 一个名为 LeftFragment 的 Java Class


如图,继承自v4包的Fragment

但是有的小伙伴会问了,上面有两个包啊,为什么要用v4的呢?系统内置的不行吗?

这里给大家解释一下:v4的Fragment可以让碎片在所有Android系统版本中保持功能一致。

打个比方:比如说在Fragment中嵌套使用Fragment,这个功能在Android 4.2 系统中才开始支持,如果你使用的是内置的Fragment,那么在4.2之前你的程序会奔溃。而使用v4就没有任何问题。

红底白字内容摘自第一行代码,我也不是很懂,但是感觉有用,所以就放上来了。

Java类代码如下

public class LeftFragment extends Fragment {
//    重写onCreateView方法

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        此处数据类型为View,所以直接返回inflater即可
        return inflater.inflate(R.layout.left_fragment,container,false);
    }
}

仅仅是重写了onCreateView方法即可

右碎片同理在此不赘述。

碎片写完后,在主活动中声明一下

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <!--注意,fragment必须要有id,否则无法编译-->
    <fragment
        android:id="@+id/left_fragment"
        android:name="com.loser.fragmenttext.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.loser.fragmenttext.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />
</LinearLayout>

可以看到,name属性写的是刚才定义的全路径包名

id属性一定要有。fragment标签必须要有id否则无法通过编译。

至此,一个简单的碎片静态加载已经完成。

返回目录


猜你喜欢

转载自blog.csdn.net/qq_38376757/article/details/79850249
今日推荐