Android改变边缘效果EdgeEffect的颜色
我们平时经常可以看到,Android可滚动的控件像ScrollView、RecyclerView等滑动到顶部或者底部时会出现一个波浪形的边缘效果,在不同的版本系统上显示的颜色有所不同,如果项目中遇到要修改它的颜色的需求,那么要如何去做呢?
以ScrollView为例,控制ScrollView上下滑动边界的阴影的效果
private EdgeEffect mEdgeGlowTop;
private EdgeEffect mEdgeGlowBottom;
@Override
public void setOverScrollMode(int mode) {
if (mode != OVER_SCROLL_NEVER) {
if (mEdgeGlowTop == null) {
Context context = getContext();
mEdgeGlowTop = new EdgeEffect(context);
mEdgeGlowBottom = new EdgeEffect(context);
}
} else {
mEdgeGlowTop = null;
mEdgeGlowBottom = null;
}
super.setOverScrollMode(mode);
}
在onTouchEvent里 通过如下方式进行调用
if (pulledToY < 0) {
mEdgeGlowTop.onPull((float) deltaY / getHeight(),
ev.getX(activePointerIndex) / getWidth());
if (!mEdgeGlowBottom.isFinished()) {
mEdgeGlowBottom.onRelease();
}
} else if (pulledToY > range) {
mEdgeGlowBottom.onPull((float) deltaY / getHeight(),
1.f - ev.getX(activePointerIndex) / getWidth());
if (!mEdgeGlowTop.isFinished()) {
mEdgeGlowTop.onRelease();
}
}
if (mEdgeGlowTop != null
&& (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
postInvalidateOnAnimation();
}
因此只需要mEdgeGlowTop ,mEdgeGlowBottom 的颜色显示,EdgeEffect里有如下方法:
/**
* Set the color of this edge effect in argb.
*
* @param color Color in argb
*/
public void setColor(@ColorInt int color) {
mPaint.setColor(color);
}
mEdgeGlowTop,mEdgeGlowBottom 为私有方法,因此通过反射的方式进行调用
public void setEdgeColor() {
if (Build.VERSION.SDK_INT >= 21) {
try {
Class<?> c = Class.forName("android.widget.ScrollView");
Field acEdgeGlowTop = c.getDeclaredField("mEdgeGlowTop");
Field acEdgeGlowBottom = c.getDeclaredField("mEdgeGlowBottom");
acEdgeGlowTop.setAccessible(true);
acEdgeGlowBottom.setAccessible(true);
EdgeEffect edgeEffect = new EdgeEffect(this);
edgeEffect.setColor(Color.RED);
acEdgeGlowTop.set(mScrollView, edgeEffect);
acEdgeGlowBottom.set(mScrollView, edgeEffect);
} catch (Exception e) {
e.printStackTrace();
}
}
}
BingGo,结束!!