Fragment通常是當作某Activity的使用者介面使用,而且可將自身的版面配置提供給Activity,可以讓我們將所需的介面都放在裡面,在進行頁面切換時就直接轉換其他顯示的內容。
首先新增一個Fragment1.Activity
並在fragment_1.xml設定文字
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns: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"
    tools:context=".Fragment1">
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is Fragment1"
        android:textSize="30sp"
        android:textColor="#2196F3"/>
</FrameLayout>
回到activity_main.xml新增FragmentContainerView
<?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:layout_height="match_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        
        <androidx.fragment.app.FragmentContainerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/fragment_container_view" />
    </LinearLayout>
</LinearLayout>
MainActivity程式設計
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //使用getSupportFragmentManager()獲取fragmentM
        FragmentManager fragmentM=getSupportFragmentManager();
        //在 Activity中進行新增、移除或替換片段時,可以使用beginTransaction()方法
        FragmentTransaction fragmentT=fragmentM.beginTransaction();
        //將Fragment1加入fragmentT,並顯示出來
        Fragment1 fragment1 =new Fragment1();
        fragmentT.add(R.id.fragment_container_view,fragment1,"frag");
        fragmentT.show(fragment1);
        //完成設定後,呼叫commit()執行
        fragmentT.commit();
    }
}
結果圖