您当前的位置: 首页 > 

蓝不蓝编程

暂无认证

  • 0浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

底部导航栏BottomNavigationView+ViewPager+Fragment

蓝不蓝编程 发布时间:2019-07-26 17:41:45 ,浏览量:0

实现效果:

实现方案
  1. 主界面xml(包含viewPager和BottomNavigationView)


    

    

  1. 底部菜单:bottom_navigation_main.xml

    
    
    

  1. MainActivity
class MainActivity : AppCompatActivity() {

    private val favoritesTabIndex = 0
    private val schedulesTabIndex = 1
    private val mineTabIndex = 2

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

        val fragments = getFragments()

        vp.adapter = object : FragmentStateAdapter(this) {
            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }

            override fun getItemCount(): Int {
                return fragments.size
            }
        }
        //禁用左右滑动切换页签
        vp.isUserInputEnabled = false

        bottomNavigationView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.action_favorites -> {
                    vp.setCurrentItem(favoritesTabIndex, false)
                }
                R.id.action_schedules -> {
                    vp.setCurrentItem(schedulesTabIndex, false)
                }
                R.id.action_music -> {
                    vp.setCurrentItem(mineTabIndex, false)
                }
            }
            true
        }
    }

    private fun getFragments(): ArrayList {
        val fragments = ArrayList(3)

        val favoritesFragment = BaseFragment()
        var bundle = Bundle()
        bundle.putString("title", getString(R.string.favorites))
        favoritesFragment.arguments = bundle

        val schedulesFragment = BaseFragment()
        bundle = Bundle()
        bundle.putString("title", getString(R.string.schedules))
        schedulesFragment.arguments = bundle

        val mineFragment = BaseFragment()
        bundle = Bundle()
        bundle.putString("title", getString(R.string.mine))
        mineFragment.arguments = bundle

        fragments.add(favoritesFragment)
        fragments.add(schedulesFragment)
        fragments.add(mineFragment)
        return fragments
    }
}
源代码:

https://github.com/cxyzy1/bottomNavigationViewSample.git

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0422s