[Android] Fragment Sample


Posted by imcloudwu on 2021-03-12

Fragment Container

    //Container1
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/container1"
        android:background="#4CAF50"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    //Container2
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/container2"
        android:background="#2196F3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Static Sample

class StaticSampleFragment : Fragment(R.layout.id)

Variable Sample

class VariableSampleFragment:Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.id,container,false)

        //Read arguments
        arguments?.getString("title")?.let {
            val textView = view.findViewById<TextView>(R.id.textView)
            textView.text = it
        }

        return view
    }
}

Activity

    fun showFragment(){

        //Fragment
        val fragment1 = VariableSampleFragment()
        val fragment2 = StaticSampleFragment()

        //Bundle
        val bundle1 = Bundle()
        bundle1.putString("title","from bundle 1")
        val bundle2 = bundleOf("title" to "from bundle 2")

        //Set arguments
        fragment1.arguments = bundle1
        fragment2.arguments = bundle2

        //Sample1
        supportFragmentManager.beginTransaction().replace(R.id.container1,fragment1).commit()

        //Sample2
        supportFragmentManager.commit {
            setReorderingAllowed(true) //Google recommend add this
            replace(R.id.container2,fragment2)
        }
    }

#andorid #Kotlin #fragment







Related Posts

DOM - 事件傳遞機制

DOM - 事件傳遞機制

Day02 為資料命名

Day02 為資料命名

DB 基礎 - N+1 problem, Transaction, ACID

DB 基礎 - N+1 problem, Transaction, ACID


Comments