BottomNavigationView + Fragment 实现底部导航栏

目标

实现底部导航栏

效果图

主要代码

  1. 添加依赖:
    implementation 'com.google.android.material:material:1.2.1'

  1. 布局文件: activity_main.xml



    

    

  1. 主界面代码:MainActivity
class MainActivity : AppCompatActivity() {
    private var lastIndex = 0
    private var mFragments = mutableListOf()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initBottomNavigation()
        initData()
    }

    private fun initData() {
        mFragments = ArrayList()
        mFragments.add(Fragment1())
        mFragments.add(Fragment2())
        // 初始化展示MessageFragment
        setFragmentPosition(0)
    }

    private fun initBottomNavigation() {
        bottomNavigationView.setOnNavigationItemSelectedListener(BottomNavigationView.OnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.menu_message -> setFragmentPosition(0)
                R.id.menu_contacts -> setFragmentPosition(1)
                else -> { }
            }
            true
        })
    }

    private fun setFragmentPosition(position: Int) {
        val ft = supportFragmentManager.beginTransaction()
        val currentFragment = mFragments[position]
        val lastFragment = mFragments[lastIndex]
        lastIndex = position
        ft.hide(lastFragment)
        if (!currentFragment.isAdded) {
            supportFragmentManager.beginTransaction().remove(currentFragment).commit()
            ft.add(R.id.ll_frameLayout, currentFragment)
        }
        ft.show(currentFragment)
        ft.commitAllowingStateLoss()
    }
}
  1. Fragment
class Fragment1 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val tv = TextView(context)
        tv.text = "第一页"
        tv.gravity = Gravity.CENTER
        return tv
    }
}
class Fragment2 : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val tv = TextView(context)
        tv.text = "第二页"
        tv.gravity = Gravity.CENTER
        return tv
    }
}
  1. 菜单:main_bottom_navigation.xml


    
    


完整源代码

https://gitee.com/cxyzy1/navigationDemo/tree/master/bottomNavigationView

你可能感兴趣的:(BottomNavigationView + Fragment 实现底部导航栏)