kotlin之fragment

2019-05-03  本文已影响0人  故江

//布局

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

    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/rb1"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="fragment1"
            android:button="@null"
            android:gravity="center"
            android:background="#f0f"
            android:layout_weight="1"/>
        <RadioButton
            android:id="@+id/rb2"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="fragment2"
            android:button="@null"
            android:gravity="center"
            android:background="#ff0"
            android:layout_weight="1"/>
        <RadioButton
            android:id="@+id/rb3"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="fragment3"
            android:button="@null"
            android:gravity="center"
            android:background="#0ff"
            android:layout_weight="1"/>
    </RadioGroup>
</LinearLayout>
class HomeActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        initView()
    }

    private fun initView() {
        val one = OneFragment()
        val two = TwoFragment()
        val three = ThreeFragment()
        supportFragmentManager.beginTransaction().replace(R.id.main_content,one).commit()
//点击事件
        rg!!.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb1 -> {
                    val one = OneFragment()
                    supportFragmentManager.beginTransaction().replace(R.id.main_content,one).commit()
                }

                R.id.rb2 -> {
                    val  two = TwoFragment();
                    supportFragmentManager.beginTransaction().replace(R.id.main_content,two).commit()
                }

                R.id.rb3 -> {
                    val three = ThreeFragment()
                    supportFragmentManager.beginTransaction().replace(R.id.main_content,three).commit()
                }
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读