TabLayout+ViewPager+Fragment自定义tab添加小红点(kotlin事例)

首先看哈效果:

TabLayout+ViewPager+Fragment自定义tab添加小红点(kotlin事例)_第1张图片

下面是两个布局,一个主布局,一个tab的布局

主布局很简单tablayout+viewpager:



    
    
    
    

tab的布局如下,这里加入的小红点:



    
    
        
    

主要关联代码:

var listFragment:MutableList> = mutableListOf("全部" to BureauFragment(),"待开局" to BureauFragment()
                        ,"已开局" to BureauFragment(),"已结束" to BureauFragment(),"已拒绝" to BureauFragment())
        //关键在于先关联viewpager,后修改tab布局(注意在绑定了viewpager后tablayout的tab已经被设置了,所以做修改操作就好了)
        mViewPager.adapter = TabPagerAdapter(supportFragmentManager,listFragment)
        mTabLayout.setupWithViewPager(mViewPager)
        mViewPager.currentItem = 0
        listFragment.forEachIndexed { i, pair ->
            //设置自定义显示小红点的布局
            var tab = mTabLayout.getTabAt(i)
            tab?.setCustomView(R.layout.item_tab_layout)
            var tvTabTitle = tab?.customView?.find(R.id.tvTabTitle)
            tvTabTitle?.text = pair.first
        }

来看看TabPagerAdapter适配器



/**
 * Author:xqt
 * Email:[email protected]
 * Date: 2019/1/5
 * Description:tablayout+viewpager+fragment
 */
class  TabPagerAdapter(fm: FragmentManager, list: MutableList>): FragmentPagerAdapter(fm) {
    private var flist = list
    //private var fm = fm
    override fun getItem(p0: Int): Fragment {
        return flist[p0].second
    }

    override fun getCount() = flist.size

    //如果不需要自定义tab的话这里就关联的每个tab的文字,当然这里需要自定义list可以自行简化下
    //override fun getPageTitle(position: Int): CharSequence? {
    //    return flist[position].first
    //}

}

 

你可能感兴趣的:(Android,kotilin)