BottomNavigationView
Posted 月盡天明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BottomNavigationView相关的知识,希望对你有一定的参考价值。
转载请注明出处:http://blog.csdn.net/crazy1235/article/details/53458022
android Support Library 25.0.0 版本中,新增加了一个API –> BottomNavigationView – 底部导航视图。
先来看看这个控件的实现效果。
基本使用
使用起来也很简单
首先在xml中引入该控件
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navi_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="@android:color/white"
app:menu="@menu/menu_bottom_navi" />
该控件的基本属性有:
app:itemIconTint : 设置菜单图标着色
app:itemTextColor : 设置菜单文本颜色
app:menu : 设置菜单
app:itemBackground : 设置导航栏的背景色
@menu/menu_buttom_navi
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_recent"
android:icon="@drawable/ic_history_black_24dp"
android:title="@string/menu_recents" />
<item
android:id="@+id/menu_favorites"
android:icon="@drawable/ic_favorite_black_24dp"
android:title="@string/menu_favorites" />
<item
android:id="@+id/menu_nearby"
android:icon="@drawable/ic_place_black_24dp"
android:title="@string/menu_nearby" />
<item
android:id="@+id/menu_navi"
android:icon="@drawable/ic_navigation_black_24dp"
android:title="@string/menu_navigation" />
</menu>
与定义普通menu布局一样。
接下来是java代码
bottomNaviView = (BottomNavigationView) findViewById(R.id.bottom_navi_view);
bottomNaviView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_recent:
break;
case R.id.menu_favorites:
break;
case R.id.menu_nearby:
break;
case R.id.menu_navi:
break;
}
return true;
}
});
对BottomNavigationView设置选择监听器就可以做一些item切换事件了。
注意事项
底部导航栏默认高度是56dp
菜单只能是3-5个
源码分析
BottomNavigationView 有几个先关的重要类
BottomNavigationView
BottomNavigationMenu
BottomNavigationMenuView
BottomNavigationPresenter
它的设计有点类似于开发中的 MVP模式。
先来看 BottomNavigationView 的构造函数
public BottomNavigationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ThemeUtils.checkAppCompatTheme(context); //检测当前主题
// Create the menu
mMenu = new BottomNavigationMenu(context);
mMenuView = new BottomNavigationMenuView(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mMenuView.setLayoutParams(params);
mPresenter.setBottomNavigationMenuView(mMenuView);
mMenuView.setPresenter(mPresenter);
mMenu.addMenuPresenter(mPresenter);
// Custom attributes
// ...省略若干代码
if (a.hasValue(R.styleable.BottomNavigationView_menu)) {
inflateMenu(a.getResourceId(R.styleable.BottomNavigationView_menu, 0)); // 加载menu
}
a.recycle();
addView(mMenuView, params); //
mMenu.setCallback(new MenuBuilder.Callback() { // 设置监听器
@Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
return mListener != null && mListener.onNavigationItemSelected(item);
}
@Override
public void onMenuModeChange(MenuBuilder menu) {}
});
}
ThemeUtils.checkAppCompatTheme(context) 是用来检测当前主题的。代码很简单,就是判断是否有 colorPrimary 属性。
class ThemeUtils {
private static final int[] APPCOMPAT_CHECK_ATTRS = {
android.support.v7.appcompat.R.attr.colorPrimary
};
static void checkAppCompatTheme(Context context) {
TypedArray a = context.obtainStyledAttributes(APPCOMPAT_CHECK_ATTRS);
final boolean failed = !a.hasValue(0);
if (a != null) {
a.recycle();
}
if (failed) {
throw new IllegalArgumentException("You need to use a Theme.AppCompat theme "
+ "(or descendant) with the design library.");
}
}
}
构造函数中接下来调用了 inflateMenu()
public void inflateMenu(int resId) {
mPresenter.setUpdateSuspended(true);
getMenuInflater().inflate(resId, mMenu);
mPresenter.initForMenu(getContext(), mMenu);
mPresenter.setUpdateSuspended(false);
mPresenter.updateMenuView(true);
}
可以看出都是调用的BottomNavigationPresenter的函数。
setUpdateSuspended(true) – 暂停修改menu
setUpdateSuspended(false) — 可以修改menu
在initForMenu()一前一后,设置一个标志来表示当前正在操作menu。
重点来看 BottomNavigationPresenter.initForMenu()
@Override
public void initForMenu(Context context, MenuBuilder menu) {
mMenuView.initialize(mMenu);
mMenu = menu;
}
函数内部又是调用的 BottomNavigationMenuView.initialize()
@Override
public void initialize(MenuBuilder menu) {
mMenu = menu;
if (mMenu == null) return;
if (mMenu.size() > mActiveButton) {
mMenu.getItem(mActiveButton).setChecked(true);
}
}
代码中就是一些简单的初始化操作。
接下来看 BottomNavigationPresenter.updateMenuView(true)
@Override
public void updateMenuView(boolean cleared) {
if (mUpdateSuspended) return;
if (cleared) {
mMenuView.buildMenuView();
} else {
mMenuView.updateMenuView();
}
}
第一次创建Menu时,调用的是buildMenuView方法。
BottomNavigationMenuView.buildMenuView()
public void buildMenuView() {
if (mButtons != null) {
for (BottomNavigationItemView item : mButtons) {
sItemPool.release(item);
}
}
removeAllViews();
mButtons = new BottomNavigationItemView[mMenu.size()];
// 当menu item大于3个的时候,会出现缩放动画
mShiftingMode = mMenu.size() > 3;
for (int i = 0; i < mMenu.size(); i++) {
mPresenter.setUpdateSuspended(true);
mMenu.getItem(i).setCheckable(true);
mPresenter.setUpdateSuspended(false);
BottomNavigationItemView child = getNewItem();
mButtons[i] = child;
child.setIconTintList(mItemIconTint);
child.setTextColor(mItemTextColor);
child.setItemBackground(mItemBackgroundRes);
child.setShiftingMode(mShiftingMode);
// 单个item -- BottomNavigationItenView 的初始化操作
child.initialize((MenuItemImpl) mMenu.getItem(i), 0);
child.setItemPosition(i);
// 设置点击事件
child.setOnClickListener(mOnClickListener);
// 添加子视图
addView(child);
}
}
在 BottomNavigationMenuView类中定义了一个Pool对象,用来缓存BottomNavigationItemView对象。
private static final Pools.Pool<BottomNavigationItemView> sItemPool = new Pools.SynchronizedPool<>(5);
通过for循环创建了nMenu.size() 个BottomNavigationItemView 对象。
BottomNavigationItemView child = getNewItem();
mButtons[i] = child;
getNewItem()
private BottomNavigationItemView getNewItem() {
BottomNavigationItemView item = sItemPool.acquire();
if (item == null) {
item = new BottomNavigationItemView(getContext());
}
return item;
}
getNewItem() 类似于 Message.obtain() 的机制。
接着看buildMenuView() ,方法最后面,调用了 BottomNavigationItemView.initialize() ,然后调用 addView(child) 来添加子item视图。
@Override
public void initialize(MenuItemImpl itemData, int menuType) {
mItemData = itemData;
setCheckable(itemData.isCheckable());
setChecked(itemData.isChecked());
setEnabled(itemData.isEnabled());
setIcon(itemData.getIcon());
setTitle(itemData.getTitle());
setId(itemData.getItemId());
}
看一下 BottomNavigationItemView的构造函数
public BottomNavigationItemView(@NonNull Context context) {
this(context, null);
}
public BottomNavigationItemView(@NonNull Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomNavigationItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final Resources res = getResources();
int inactiveLabelSize =
res.getDimensionPixelSize(R.dimen.design_bottom_navigation_text_size);
int activeLabelSize = res.getDimensionPixelSize(
R.dimen.design_bottom_navigation_active_text_size);
mDefaultMargin = res.getDimensionPixelSize(R.dimen.design_bottom_navigation_margin);
mShiftAmount = inactiveLabelSize - activeLabelSize;
mScaleUpFactor = 1f * activeLabelSize / inactiveLabelSize;
mScaleDownFactor = 1f * inactiveLabelSize / activeLabelSize;
// 注意下面的代码
LayoutInflater.from(context).inflate(R.layout.design_bottom_navigation_item, this, true);
setBackgroundResource(R.drawable.design_bottom_navigation_item_background);
mIcon = (ImageView) findViewById(R.id.icon);
mSmallLabel = (TextView) findViewById(R.id.smallLabel);
mLargeLabel = (TextView) findViewById(R.id.largeLabel);
}
代码中映射了一个布局文件
design_bottom_navigation_item.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/design_bottom_navigation_margin"
android:layout_marginBottom="@dimen/design_bottom_navigation_margin"
android:duplicateParentState="true" />
<android.support.design.internal.BaselineLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/design_bottom_navigation_margin"
android:layout_gravity="bottom|center_horizontal"
android:duplicateParentState="true">
<TextView
android:id="@+id/smallLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/design_bottom_navigation_text_size"
android:duplicateParentState="true" />
<TextView
android:id="@+id/largeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:textSize="@dimen/design_bottom_navigation_active_text_size"
android:duplicateParentState="true" />
</android.support.design.internal.BaselineLayout>
</merge>
该布局文件由系统提供,包括一个ImageView和两个TextView。
当菜单项大于3个,切换item时,被选中的item会将largeLabel显示,将smallLabel隐藏。然后改变ImageView和TextView的margin值达到动画效果。
在BottomNavigationMenuView的构造函数中对mAnimationHelper进行了实例化
private final BottomNavigationAnimationHelperBase mAnimationHelper;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mAnimationHelper = new BottomNavigationAnimationHelperIcs();
} else {
mAnimationHelper = new BottomNavigationAnimationHelperBase();
}
当版本小于14(Android 4.0)时,是没有动画效果的。
class BottomNavigationAnimationHelperBase {
void beginDelayedTransition(ViewGroup view) {
// Do nothing.
}
}
Android 4.0及之上的版本
class BottomNavigationAnimationHelperIcs extends BottomNavigationAnimationHelperBase {
private static final long ACTIVE_ANIMATION_DURATION_MS = 115L;
private final TransitionSet mSet;
BottomNavigationAnimationHelperIcs() {
mSet = new AutoTransition();
mSet.setOrdering(TransitionSet.ORDERING_TOGETHER);
mSet.setDuration(ACTIVE_ANIMATION_DURATION_MS);
mSet.setInterpolator(new FastOutSlowInInterpolator());
TextScale textScale = new TextScale();
mSet.addTransition(textScale);
}
void beginDelayedTransition(ViewGroup view) {
TransitionManager.beginDelayedTransition(view, mSet);
}
}
代码中定义了文本缩放动画 – TextScale
然后来看 BottomNavigationItemView的点击事件。
在初始化这些子itemView的时候就设置了onClickListener
child.initialize((MenuItemImpl) mMenu.getItem(i), 0);
child.setItemPosition(i);
// 设置点击事件 child.setOnClickListener(mOnClickListener);
mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final BottomNavigationItemView itemView = (BottomNavigationItemView) v;
final int itemPosition = itemView.getItemPosition();
activateNewButton(itemPosition);
mMenu.performItemAction(itemView.getItemData(), mPresenter, 0);
}
};
activateNewButtom()
private void activateNewButton(int newButton) {
if (mActiveButton == newButton) return;
mAnimationHelper.beginDelayedTransition(this); // 产生动画
mPresenter.setUpdateSuspended(true);
mButtons[mActiveButton].setChecked(false); // 旧的被激活的按钮切换成未被激活状态
mButtons[newButton].setChecked(true); // 将新点击的按钮切换到被激活状态
mPresenter.setUpdateSuspended(false);
mActiveButton = newButton; // 记录当前被激活按钮的位置
}
先产生动画,然后切换被选中和之前选中的item的状态。
@Override
public void setChecked(boolean checked) {
mItemData.setChecked(checked);
ViewCompat.setPivotX(mLargeLabel, mLargeLabel.getWidth() / 2);
ViewCompat.setPivotY(mLargeLabel, mLargeLabel.getBaseline());
ViewCompat.setPivotX(mSmallLabel, mSmallLabel.getWidth() / 2);
ViewCompat.setPivotY(mSmallLabel, mSmallLabel.getBaseline());
if (mShiftingMode) {
if (checked) {
LayoutParams iconParams = (LayoutParams) mIcon.getLayoutParams();
iconParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
iconParams.topMargin = mDefaultMargin;
mIcon.setLayoutParams(iconParams);
mLargeLabel.setVisibility(VISIBLE);
ViewCompat.setScaleX(mLargeLabel, 1f);
ViewCompat.setScaleY(mLargeLabel, 1f);
} else {
LayoutParams iconParams = (LayoutParams) mIcon.getLayoutParams();
iconParams.gravity = Gravity.CENTER;
iconParams.topMargin = mDefaultMargin;
mIcon.setLayoutParams(iconParams);
mLargeLabel.setVisibility(INVISIBLE);
ViewCompat.setScaleX(mLargeLabel, 0.5f);
ViewCompat.setScaleY(mLargeLabel, 0.5f);
}
mSmallLabel.setVisibility(INVISIBLE);
} else {
if (checked) {
LayoutParams iconParams = (LayoutParams) mIcon.getLayoutParams();
iconParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
iconParams.topMargin = mDefaultMargin + mShiftAmount;
mIcon.setLayoutParams(iconParams);
mLargeLabel.setVisibility(VISIBLE);
mSmallLabel.setVisibility(INVISIBLE);
ViewCompat.setScaleX(mLargeLabel, 1f);
ViewCompat.setScaleY(mLargeLabel, 1f);
ViewCompat.setScaleX(mSmallLabel, mScaleUpFactor);
ViewCompat.setScaleY(mSmallLabel, mScaleUpFactor);
} else {
LayoutParams iconParams = (LayoutParams) mIcon.getLayoutParams();
iconParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
iconParams.topMargin = mDefaultMargin;
mIcon.setLayoutParams(iconParams);
mLargeLabel.setVisibility(INVISIBLE);
mSmallLabel.setVisibility(VISIBLE);
ViewCompat.setScaleX(mLargeLabel, mScaleDownFactor);
ViewCompat.setScaleY(mLargeLabel, mScaleDownFactor);
ViewCompat.setScaleX(mSmallLabel, 1f);
ViewCompat.setScaleY(mSmallLabel, 1f);
}
}
refreshDrawableState();
}
mShiftingMode 表示是否偏移值。当菜单个数大于3时,为true。
demo传送门:
以上是关于BottomNavigationView的主要内容,如果未能解决你的问题,请参考以下文章
BottomNavigationView - 如何避免重新创建片段并重用它们
在片段转换期间隐藏 BottomNavigationView
片段内容未在 BottomNavigationView FragmentTransaction 上加载
从bottomNavigationView导航到片段B时保存片段A的状态