[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

[JavaScript] NPM 是什麼?怎麼用?

[JavaScript] NPM 是什麼?怎麼用?

Find the winner of Tic-Tac-Toe

Find the winner of Tic-Tac-Toe

網際網路是什麼?

網際網路是什麼?


Comments