android系统自带的BottomNavigationBar用起来是很方便,就是固定了大小,即使在xml里面配置了高度。当你设置的高度大于56dp,你会发现底部有两层,后面一层白底的布局比BottomNavigationBar高,露出来了。在看了BottomNavigationBar源码后发现在加载它的布局的时候,把inflate出来的view添加到BottomNavigationBar上了。
private void init() {
// MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_padded_height)));
// marginParams.setMargins(0, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_top_margin_correction), 0, 0);
setLayoutParams(new ViewGroup.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)));
LayoutInflater inflater = LayoutInflater.from(getContext());
//这里把this作为root,并且设置了attachToRoot为true
View parentView = inflater.inflate(R.layout.bottom_navigation_bar_container, this, true);
mBackgroundOverlay = parentView.findViewById(R.id.bottom_navigation_bar_overLay);
//这个就是加载出来的布局文件,是一个FrameLayout
mContainer = parentView.findViewById(R.id.bottom_navigation_bar_container);
//这里是放用户添加的的导航item,是一个LinearLayout
mTabContainer = parentView.findViewById(R.id.bottom_navigation_bar_item_container);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setOutlineProvider(ViewOutlineProvider.BOUNDS);
} else {
//to do
}
ViewCompat.setElevation(this, mElevation);
setClipToPadding(false);
}
我们知道,如果attachToRoot了,返回的就是root布局,这里也告诉我们在inflate列表类View的item时候不能调用
inflater.inflate($layoutId$,root);因为该方法会调用inflater.inflate($layoutId$,root,root != null);即inflater.inflate($layoutId$,root,true);
会把root作为结果返回。这自然不是你想要的。要么调用inflater.inflate($layoutId$,null);非要带上root的时候,调用inflater.inflate($layoutId$,root,false);
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];