类似于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>