和我一起學Fragment – Philip Hsinh – Medium

[ad_1]

圖片取自Google官方網站: shorturl.at/FLNPT
class exampleFragment : Fragment()
override enjoyable onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {

return inflater.inflate(R.format.exampleFragment, container, false)
}

<?xml model="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:instruments="http://schemas.android.com/instruments"
android:layout_width="match_parent"
android:layout_height="match_parent"
instruments:context=".MainActivity">

<FrameLayout
android:id="@+id/currentFragment"
android:identify="com.instance.fragment.exampleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottomNavBar"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
...
</RelativeLayout>

  1. 準備好要換進來的Fragment的程式碼和設計(參照上面exampleFragment的寫法)
  2. 在需要寫切換畫面功能的Fragment類別裏面寫好觸發場景(set off),譬如最常見的就是Button的setOnClickListener{}。
override enjoyable onCreate(savedInstanceState: Bundle?) {
...
switchFragmentButton.setOnClickListener {
replaceFragment(AnotherExampleFragment())
}
non-public enjoyable replaceFragment(newFragment: Fragment) {
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.substitute(R.id.exampleFragment, newFragment)
transaction.commit()
  1. 我們準備用button作為trigger,觸發replaceFragment()這個方法
  2. 在replaceFragment裏面定義好如下幾個幫助我們切換畫面的大將:
  3. 在Activity中用supportFragmentManager獲取FragmentManager實體,由fragmentManager來管理我們Fragment的生死。再調用這個fragmentManager的beginTransaction()方法表示我們要準備請她做事情。
  4. 我們把想跳轉的新Fragment當作參數塞進去
transaction.substitute(想換誰,換成誰)
transaction.commit() // 最關鍵的一步,commit就是宣告我們定義好了要做的事情,拜託執行下去
non-public enjoyable replaceFragment(newFragment: Fragment) {
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
...
transaction.addToBackStack(null) // 在commit前面添加這一行,實現backStack特性
...
}
override enjoyable onViewCreated(view: View, savedInstanceState: Bundle?) {
tremendous.onViewCreated(view, savedInstanceState)
button_sendMessage?.setOnClickListener {
replaceFragment(Fragment4())
}val bundle: Bundle? = arguments
if (bundle != null) {
displayText.textual content = bundle.getString("message")
}
}

[ad_2]

Source_link

Leave a Comment