拿这个FrameLayout
绘制阴影和这个渐变可绘制 xml:
public class DrawShadowFrameLayout extends FrameLayout {
private Drawable mShadowDrawable;
private final int mShadowElevation = 8;
private int mWidth;
private int mHeight;
private boolean mShadowVisible = true;
public DrawShadowFrameLayout(Context context) {
this(context, null, 0);
}
public DrawShadowFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawShadowFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mShadowDrawable = ContextCompat.getDrawable(getContext(), R.drawable.shadow);
if (mShadowDrawable != null) {
mShadowDrawable.setCallback(this);
}
setWillNotDraw(!mShadowVisible);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
updateShadowBounds();
}
private void updateShadowBounds() {
if (mShadowDrawable != null) {
mShadowDrawable.setBounds(0, 0, mWidth, mShadowElevation);
}
ViewCompat.postInvalidateOnAnimation(this);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mShadowDrawable != null && mShadowVisible) {
getBackground().setBounds(0, mShadowDrawable.getBounds().bottom, mWidth, mHeight);
mShadowDrawable.draw(canvas);
}
}
public void setShadowVisible(boolean shadowVisible) {
setWillNotDraw(!mShadowVisible);
updateShadowBounds();
}
int getShadowElevation() {
return mShadowVisible ? mShadowElevation : 0;
}
}
把你包裹BottomNavigationView
在这个布局里面,比如:
<DrawShadowFrameLayout>
<BottomNavigationView />
</DrawShadowFrameLayout>
不幸的是,原生阴影是在视图下绘制的,我们必须自己模仿这个向上的阴影。
不要忘记添加android:elevation="8dp"
。DrawShadowFrameLayout
另一种方法是扩展 BottomNavigationView
和覆盖draw()
来做同样的事情。这将帮助您FrameLayout
在视图层次结构中放松一个。