我们先看一下要实现的效果,如下图,底部的导航,未选中情况下,是一张图片,选中的时候,是图片加文字,实现起来,有很多种方式,但是,我们要考虑到复用性,比如,现在是三个,后来,老板一拍脑袋,再增加一个,或者两个,怎么办?
考虑到这个问题,我自己再写的时候,就没把它写死,而是根据,你导航tab的个数,来写,思路,就是先定义一个LinearLayout,设置属性为横向,设置几个,我们就动态的往这个LinearLayout里去添加几个子元素,当然了,权重是等分比的。
有了这个思路,那么代码写起来就很简单了,全部代码如下,大家可以看到,这里定义了两个数组,用来存放点击和未点击的图标,看设置tab那个方法里,就是根据你这个数组,来添加的元素,目前是三个,想再加的话,你往数组里添加对应的元素就可以了。
对于这个自定义View,需要补充的是,选中和未选中,采用的是隐藏文字View的方法,具体还得需要看以下代码:
class MainBottomTab(context: Context?, attrs: AttributeSet?) : RelativeLayout(context, attrs) {
private var mViewPager:NoScrollViewPager?=null
//选择
private var mSelected = arrayOf(
R.drawable.home_selected,
R.drawable.cinema_selected,
R.drawable.account_selected
)
//未选择
private var mNormal = arrayOf(
R.drawable.home_normal,
R.drawable.cinema_normal,
R.drawable.account_normal
)
//选中文字
private var mSelectedTxt= arrayOf(
"电影","影院","我的"
)
private var mLayoutBottom: LinearLayout? = null
init {
var view = View.inflate(context, R.layout.layout_main_bottom, null)
mLayoutBottom = view.findViewById<View>(R.id.layout_main) as LinearLayout?
addView(view)
}
//设置Tab
fun setBottomTab(position: Int) {
mLayoutBottom!!.removeAllViews()
for ((index, value) in mSelected.withIndex()) {
var view = View.inflate(context, R.layout.layout_bottom_item, null)
var imageView = view.findViewById<ImageView>(R.id.layout_main_pic)
var mainText=view.findViewById<TextView>(R.id.layout_main_text)
var mainLayoutBottom=view.findViewById<RelativeLayout>(R.id.layout_main_bottom)
mainText.setText(mSelectedTxt[index])
if (position == index) {//选中
var drawable = mSelected[index]
imageView.setImageDrawable(context.resources.getDrawable(drawable))
mainText.visibility= View.VISIBLE
mainLayoutBottom.setBackgroundResource(R.drawable.layout_main_bottom)
if(mViewPager!=null){
mViewPager!!.setCurrentItem(index)//切换页面
}
} else {
var drawable = mNormal[index]
imageView.setImageDrawable(context.resources.getDrawable(drawable))
mainText.visibility= View.GONE
mainLayoutBottom.setBackgroundResource(R.color.color_1c2)
}
mLayoutBottom!!.addView(view)
var params = view.layoutParams as LinearLayout.LayoutParams
params.weight = 1F
params.gravity=Gravity.CENTER
view.layoutParams = params
//点击
view.setOnClickListener {
setBottomTab(index)
}
}
}
/**
*@Author:AbnerMing
*@Description:绑定Viewpager
*@Date:2019/9/21 15:20
* @Param
* @return
*/
fun bindViewPager(mMainViewPager: NoScrollViewPager) {
mViewPager=mMainViewPager
}
}