带前景色的容器
如果您用google play会发现当按下应用图标时,会出现一透明色覆盖在图标上面(如下图)。注意这个不是background效果而是foreground或是遮罩(overlay)。
实现这种效果通常的思路是在容器(LinearLayout、RelativeLayout等)画玩子控件后,再画一透明色或透明图片在容器顶层达到覆盖遮罩的效果。不过这种思路还需重载onTouchEvent来监听手指按下、抬起等,而且实现将非常的繁琐。
幸好还有更加便捷的实现方法:那就是google在View类中提供的getDrawableState、drawableStateChanged方法。getDrawableState返回的是视图状态,而drawableStateChanged即是状态发生变化时调用。ok!有了这2个api我们就可以挂接到Drawable的callback设置相应的状态(setState),从而根据不同的状态绘制不同的drawable状态(selector).
下面是一个简单的控件代码
package com.droidwolf.overlay; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.LinearLayout; public class OverlayContainer extends LinearLayout { private Drawable mForeground; private final Rect mBound = new Rect(); public OverlayContainer(Context context) { super(context); } public OverlayContainer(Context context, AttributeSet attrs) { super(context, attrs); } public Drawable getForegroundDrawable() { return mForeground; } public void setForegroundDrawable(Drawable draw) { if (draw == mForeground) { return; } if (mForeground != null) { unscheduleDrawable(mForeground); mForeground.setCallback(null); } mForeground = draw; if (draw != null) { if (draw.isStateful()) { draw.setState(getDrawableState()); } draw.setCallback(this); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mBound.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mForeground != null && mForeground.isStateful()) { mForeground.setState(getDrawableState()); } } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || (who == mForeground); } @Override public void dispatchDraw(Canvas canvas) { if (mForeground == null) { super.dispatchDraw(canvas); } else { final int sc = canvas.save(); super.dispatchDraw(canvas); mForeground.setBounds(mBound); mForeground.draw(canvas); canvas.restoreToCount(sc); } } }
需要注意的是如果容器的子控件设置了OnClickListener事件,mForeground绘画状态就有可能失效,这时您需要添加addStatesFromChildren属性并设置为true。
另:FrameLayout已经实现了foreground功能。
相关推荐
yangkang 2020-11-09
alien 2020-11-15
ChlatZed 2020-11-11
远远的山 2020-11-09
xysoul 2020-11-03
onepiecedn 2020-10-29
lnkToKing 2020-10-29
ChlatZed 2020-10-27
谢恩铭 2020-10-23
yuanye0 2020-10-15
liverlife 2020-10-10
somyjun 2020-09-29
xiaoying 2020-09-28
kunyus 2020-09-25
dusuanyun 2020-09-21
newisI 2020-09-01
afanti 2020-09-14