[toc]
之前
我们之前使用的底部菜单栏有很多种方式,我比较喜欢的是RadioGroup+RadioButton的方式进行底部菜单栏布局,这个基本可以满足日常使用,但是有个问题就是贼麻烦,字体又要selector,drawableTop又要selector,贼麻烦。
image.png新方法
新方法使用了一个库
compile 'com.ashokvarma.android:bottom-navigation-bar:1.4.1'
具体使用方法我贴代码就好了,很方便的:
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/vpMainContent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<com.ashokvarma.bottomnavigation.BottomNavigationBar
android:id="@+id/btmBarMainMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
kotlin
package com.playingjoy.FanRabbit
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.widget.Toast
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initTopViewPager()
initBottomBar()
}
/**
* 初始化上部的ViewPager
*/
private fun initTopViewPager() {
}
/**
* 初始化底部菜单栏
*/
private fun initBottomBar() {
btmBarMainMenu.setMode(BottomNavigationBar.MODE_FIXED)
btmBarMainMenu.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC)
btmBarMainMenu.backgroundColor=resources.getColor(android.R.color.black)
val homeTab=BottomNavigationItem(R.drawable.ic_launcher_background,"首页")
val gameTab=BottomNavigationItem(R.drawable.ic_launcher_background,"首页")
val tradTab=BottomNavigationItem(R.drawable.ic_launcher_background,"首页")
val centerTab=BottomNavigationItem(R.drawable.ic_launcher_background,"首页")
btmBarMainMenu.addItem(homeTab)
.addItem(gameTab)
.addItem(tradTab)
.addItem(centerTab)
.setFirstSelectedPosition(0)
.initialise()
btmBarMainMenu.setTabSelectedListener(object :BottomNavigationBar.OnTabSelectedListener {
override fun onTabReselected(position: Int) {
}
override fun onTabUnselected(position: Int) {
}
override fun onTabSelected(position: Int) {
Toast.makeText(this@MainActivity,"this is the $position",Toast.LENGTH_SHORT).show()
}
})
}
}
其中如果我们需要修改图片和字体的间距的话,我们可以在values/dimens文件下设置新的dimen属性:
image.png
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="fixed_height_bottom_padding">6dp</dimen>
</resources>
默认是10dp,数值越小间距越大
image.png
网友评论