<?xml version="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#92F3C9"tools:context=".ExampleFragment"><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="Hi there! I'm a fragment"android:textColor="#43CDE4"android:textSize="30sp"/></FrameLayout>
在这里,我在 FrameLayout 中添加了一个 TextView。
为fragment创建一个 java 文件,如下所示 -
FragmentExample.java
packagecom.example.addfragmentprogramatically;importandroid.os.Bundle;importandroidx.fragment.app.Fragment;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;publicclassExampleFragmentextendsFragment{@OverridepublicvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);}@OverridepublicViewonCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){// Inflate the layout for this fragmentreturn inflater.inflate(R.layout.fragment_example, container,false);}}