Android碎片学习(一)——简单用法

一、引入

碎片(Fragment)是一种可以嵌入在活动中的UI碎片,可以理解为一个迷你型的活动。

先创建一个平板模拟器:
在这里插入图片描述
接着新建一个day06_Fragment的空项目开始写代码

二、简单用法

1、碎片布局

左侧碎片布局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">
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="button"
        />

</LinearLayout>

右侧碎片布局right_frgment

<?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="#00ff00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="50sp"
        android:text="右侧碎片布局"
        />

</LinearLayout>

2、类

新建一个LeftFragment类,继承自Fragment,重写onCreateView()

public class LeftFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.left_fragment, container, false);
    }
}

同样的新建一个RightFragment类:

public class RightFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.right_fragment, container, false);
    }
}

3、主布局

主布局,使用<fragment>标签添加碎片,通过android:name指明要添加的碎片类名,注意还要写包名

<?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:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.example.day06_fragment.LeftFragment"
        android:id="@+id/left_fragment"
        />
    
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.example.day06_fragment.RightFragment"
        android:id="@+id/right_fragment"
        />
</LinearLayout>

4、运行

可以看到碎片平分了布局
在这里插入图片描述

发布了156 篇原创文章 · 获赞 13 · 访问量 7230

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/103981510
今日推荐