概述

編輯 activity 的 layout xml 來指定要加入的 fragment 是使用上最基本的方式,之後還可以配合 FragmentManager 來替換或加入新的 fragment。

相關檔案

MainActivity.kt

activity_main.xml

FirstFragment.kt

fragment_first.xml

函式庫依賴

程式碼實作

首先建立一個專案,名稱為 Fragment Lab 01,其 package name 會是 com.example.fragmentlab01

FirstFragment.kt

建立一個新的 Blank Fragment,刪除不需要的部份,只需留下以下程式碼。

class FirstFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }
}

fragment_first.xml

text 改為 First Fragment,並將 textSize 設為 24sp,以方便觀察。

<?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=".FirstFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp"
        android:text="First Fragment" />

</FrameLayout>

MainActivity.kt

無需更動,使用 AndroidStudio 自動產生的檔案即可

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
}

activity_main.xml

因為我只打算放 Fragment,所以可以改為這樣。

注意: android:name 的值,需要是 FirstFragment 完整的 package 名稱,這會隨著專案的設定而有所不同。

<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
    xmlns:android="<http://schemas.android.com/apk/res/android>"
    android:id="@+id/fragmentContainerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
		android:name="com.example.fragmentlab01.FirstFragment"
    />

如果你還有其他的 View 要加進去,也可以配合其他的 Layout 來使用,舉例如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="<http://schemas.android.com/apk/res/android>"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.example.fragmentlab01.FirstFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

可以依需要加入 Toolbar 或其他的 View。

參考資料

developers Guide: About Fragment

devolopers Guide: Navigation component

Android Fragments: FragmentContainerView

Last modified: 2023 年 3 月 23 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.