Android用Kotlin写一个TabLayout+ViewPager

时间:2024-03-20 10:53:20

今天突然有兴趣,想学习kotlin,就想撸一个页面切换。。

Android用Kotlin写一个TabLayout+ViewPager

Android用Kotlin写一个TabLayout+ViewPager

implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'

这两个是需要导入的包,升级了as 3.0把compile 换成了implementation


在xml中写入

<android.support.design.widget.TabLayout
        android:id="@+id/tab_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="center"
        app:tabMode="fixed" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

然后写一个pagerAdapter

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter

/**
 * Created by xxx on 2018/5/3.
 */
class KotlinPagerAdapter(var mList: List<Fragment>, fm: FragmentManager?) : FragmentStatePagerAdapter(fm) {
    override fun getItem(position: Int): android.support.v4.app.Fragment {
        return mList[position]
    }

    override fun getCount(): Int {
        return mList.size
    }

}

再看看activity里

import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import com.example.ymh.kotlin_study.Util.KotlinPagerAdapter
import com.example.ymh.kotlin_study.View.ItemOneFragment
import com.example.ymh.kotlin_study.View.ItemTwoFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), TabLayout.OnTabSelectedListener {
    override fun onTabReselected(tab: TabLayout.Tab?) {
        //tab重新选择的时候回调
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        //tab未被选择的时候回调
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        //tab被选的时候回调
        vp_main.currentItem = tab!!.position
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
      setTab()
      setItem()
      initView()

vp_main.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tab_main))
    } fun setTab () {
        val tab1:ItemOneFragment = ItemOneFragment() val tab2:
        ItemTwoFragment = ItemTwoFragment() var list = listOf < Fragment > (tab1, tab2)
        vp_main.adapter = KotlinPagerAdapter(list, supportFragmentManager) //让tab和viewpager关联起来
        tab_main.setupWithViewPager(vp_main)
    } fun setItem () {
        val list = listOf < String > ("JAVA", "KOTLIN")tab_main.getTabAt(0) ?.
        text = list[0] tab_main.getTabAt(1) ?.text = list[1]
    }
}

fragment自己创建写好就可以了