Android Fragment 静态加载

类似于Spring Boot页面渲染模板thymeleaf中的fragment,由一些视图组件构成,可作一个大的组件使用,好处在于提高代码复用性,同时也有助于在多终端屏幕上采用不同组合适配

Fragment生命周期比Activity稍微多一点

Fragment的创建和加载

在layout中创建fragment视图文件

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


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@color/colorAccent"
        android:text="Hello,World!" />
</LinearLayout>

为fragment创建一个类,继承Fragment类,随后实现父类方法onCreateView()

package learn.example.calculator;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class TestFragment extends Fragment{
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载视图文件
        View view = inflater.inflate(R.layout.test_fragment, container, false);
        return view;
    }
}

在需要使用Fragment的视图的文件中,用fragment标签引入

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    // 视图中调用了三次fragment

    <fragment
        android:id="@+id/fragment1"
        android:name="learn.example.calculator.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    />

    <fragment
        android:id="@+id/fragment2"
        android:name="learn.example.calculator.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <fragment
        android:id="@+id/fragment3"
        android:name="learn.example.calculator.TestFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

猜你喜欢

转载自www.cnblogs.com/esrevinud/p/12148899.html
今日推荐