参考文章Android 底部导航栏 (底部 Tab) 最佳实践
实现功能很普通,只需要item的布局自己写,传入标题,选中的和未选中的图标数组。然后配合ViewPager
用法如下
fragmentList = new ArrayList<>();
mTitleList = new String[]{"首页", "发现", "我的"};
mUnSelectedIcon = new int[]{R.mipmap.home_icon, R.mipmap.contacts_icon, R.mipmap.my_icon};
mSelectedIcon = new int[]{R.mipmap.home_icon_1, R.mipmap.contacts_icon_1, R.mipmap.my_icon_1};
fragmentList.add(new FragmentOne());
fragmentList.add(new FragmentTwo());
fragmentList.add(new FragmentThree());
mViewPager.setAdapter(new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragmentList))
bottom_nav.setItemViewResId(R.layout.menu_main_activity)
.setmTextList(mTitleList)
.setSelectedTextColor(getResources().getColor(R.color.common_blue))
.setNormalTextColor(getResources().getColor(R.color.common_gray))
.setNormalIconArray(mUnSelectedIcon)
.setSelectedIconArray(mSelectedIcon)
.setListener(this)
.build();//默认选中index 为0的item
//item的点击事件
@Override
public void onItemSelected(View view, int position) {
bottom_nav.setCurrentItem(position);
mViewPager.setCurrentItem(position,false);
}
//ViewPager的滑动监听
@Override
public void onPageSelected(int position) {
bottom_nav.setCurrentItem(position);
}
不过还是先贴一下效果
关键点:
- item布局自定义,且不需要制定id,那怎么在封装的组合控件里找到对应的TextView和ImageView
- 设置item布局的layoutParams
- 优雅的记录点击item的索引
部分代码:
-
关键点1代码
ViewGroup view = (ViewGroup) LayoutInflater.from(getContext()).inflate(itemViewResId, this,false); //这里不通过id获取控件,因为动态添加ID不好设置 for (int t = 0; t < view.getChildCount(); t++) { if (view.getChildAt(t) instanceof TextView){ TextView textView = (TextView) view.getChildAt(t); textView.setText(mTitleList[i]); textViewList.add(textView); } else if (view.getChildAt(t) instanceof ImageView) { imageViewList.add((ImageView) view.getChildAt(t)); } }
-
关键点2代码
//设置ItemView布局,平分容器且居中 LayoutParams params = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1); view.setLayoutParams(params);
-
关键点3代码
view.setTag(mTabs.size());//通过记录addView之前的数组大小设置tag,记录view的索引
完整代码github