Activity和fragment的數(shù)據(jù)交互(1)-Fragment的添加

Activity和fragment的關(guān)系

fragment 英文翻譯過(guò)來(lái)是是碎片的意思,它可以說(shuō)是activity的一部分,不能夠獨(dú)立的存在,需要有一個(gè)activity載體,一個(gè)fragment可以被多個(gè)activity復(fù)用。相當(dāng)于fragment可以隨意被挪動(dòng),而activity則是固定不變的。fragment復(fù)用起來(lái)就更加的靈活了。

怎么添加fragment到activity中呢

既然fragment不能獨(dú)立的存在,需要一個(gè)activity作為載體。那怎么才能夠添加到fragment呢。

  • 在java代碼中添加
  1. 在你的布局xml中放置一個(gè)布局,用做來(lái)添加你的Fragment。任意的布局都可以,一般使用FragmeLayout來(lái)加載,小菜鳥(niǎo)也不知道為什么,只是每次都這樣做。
<?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"
    android:orientation="vertical"
    tools:context=".SecondActivity">

// 承載Fragment的布局
    <FrameLayout android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
  1. 在你的載體activity中用代碼添加布局
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val fragment = OneFragment()
        // 獲取manager開(kāi)始事務(wù),添加你的Fragment實(shí)例,然后提交
        supportFragmentManager.beginTransaction().add(R.id.fl_content, fragment).commit()
        // Fragment也可以替換的哦
        val otherFragment = SecondFragment()
        supportFragmentManager.beginTransaction().replace(R.id.fl_content, otherFragment).commit()
    }
  • 在xml中添加

在你的布局文件中添加fragment標(biāo)簽, 這個(gè)時(shí)候一定要標(biāo)id哦, java代碼中不需要做任何處理

// name 的值,需要填你的Fragment的位置:包名+類名, 
<fragment android:name="com.example.myapplication.fragment.OneFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/one_fragment" />
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容