Android改变边缘效果EdgeEffect的颜色

  我们平时经常可以看到,Android可滚动的控件像ScrollView、RecyclerView等滑动到顶部或者底部时会出现一个波浪形的边缘效果,在不同的版本系统上显示的颜色有所不同,如果项目中遇到要修改它的颜色的需求,那么要如何去做呢?

1.setColor方法可以直接使用吗?

setColor
  打开Android官方文档后找到EdgeEffect类,我们可以看到该类下有个直接设置颜色的方法setColor,那么如果我们如果想修改EdgeEffect的颜色的话,是不是直接调用该方法就可以直接大功告成了呢?答案是否定的(除非要适配的系统在5.0以上),我们可以看到setColor右边有一个醒目的字眼:added in API level 21。该方法是在Api21即5.0的版本中添加进去的,在5.0以下的版本是无法使用该方法的,那么如果要适配5.0以下的机型要怎么去做呢?

2.通过源码一窥究竟

  Android 4.4(api 20)EdgeEffect的部分源码

 public EdgeEffect(Context context) {
        final Resources res = context.getResources();
        mEdge = res.getDrawable(R.drawable.overscroll_edge);  // 获取图片
        mGlow = res.getDrawable(R.drawable.overscroll_glow);  // 获取图片

        mEdgeHeight = mEdge.getIntrinsicHeight();
        mGlowHeight = mGlow.getIntrinsicHeight();
        mGlowWidth = mGlow.getIntrinsicWidth();

        mMaxEffectHeight = (int) (Math.min(
                mGlowHeight * MAX_GLOW_HEIGHT * mGlowHeight / mGlowWidth * 0.6f,
                mGlowHeight * MAX_GLOW_HEIGHT) + 0.5f);

        mMinWidth = (int) (res.getDisplayMetrics().density * MIN_WIDTH + 0.5f);
        mInterpolator = new DecelerateInterpolator();
    }
    
     public boolean draw(Canvas canvas) {
        update();

        mGlow.setAlpha((int) (Math.max(0, Math.min(mGlowAlpha, 1)) * 255));

        int glowBottom = (int) Math.min(
                mGlowHeight * mGlowScaleY * mGlowHeight / mGlowWidth * 0.6f,
                mGlowHeight * MAX_GLOW_HEIGHT);
        if (mWidth < mMinWidth) {
            // Center the glow and clip it.
            int glowLeft = (mWidth - mMinWidth)/2;
            mGlow.setBounds(glowLeft, 0, mWidth - glowLeft, glowBottom);
        } else {
            // Stretch the glow to fit.
            mGlow.setBounds(0, 0, mWidth, glowBottom);
        }

        mGlow.draw(canvas); // 绘制图片

        mEdge.setAlpha((int) (Math.max(0, Math.min(mEdgeAlpha, 1)) * 255));

        int edgeBottom = (int) (mEdgeHeight * mEdgeScaleY);
        if (mWidth < mMinWidth) {
            // Center the edge and clip it.
            int edgeLeft = (mWidth - mMinWidth)/2;
            mEdge.setBounds(edgeLeft, 0, mWidth - edgeLeft, edgeBottom);
        } else {
            // Stretch the edge to fit.
            mEdge.setBounds(0, 0, mWidth, edgeBottom);
        }
        mEdge.draw(canvas); // 绘制图片

        if (mState == STATE_RECEDE && glowBottom == 0 && edgeBottom == 0) {
            mState = STATE_IDLE;
        }

        return mState != STATE_IDLE;
    }

  上面是4.4 EdgeEffect的部分源码,我们可以看出EdgeEffect的边缘效果是通过两张图片来进行绘制的,那么如果我们可以修改图片的颜色,那不就可以修改EdgeEffect所绘制出来的波浪效果的颜色了吗?

3.如何修改4.4以下的EdgeEffect的显示颜色

下面是具体步骤

1.找到系统绘制边缘的图片资源id

  从源码可以看出,绘制边缘的图片资源id如下:
  R.drawable.overscroll_edge
  R.drawable.overscroll_glow

2.替换为自己设置的图片

3.设置图片的颜色

直接上代码了

public class MyScrollView {

    public MyScrollView(Context context) {
        this(context, null);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    // 通过ContextWrapperEdgeEffect里自定义的ResourcesEdgeEffect在系统获取R.drawable.overscroll_edge和R.drawable.overscroll_glow时替换为自己设置的图片
        super(new ContextWrapperEdgeEffect(context), attrs, defStyleAttr);
    }
    
    public void setEdgeEffectColor(int edgeEffectColor) {
        // 通过该方法修改颜色
        ((ContextWrapperEdgeEffect) getContext()).setEdgeEffectColor(edgeEffectColor);
    }
}
    
/**
 * 自定义滑动到顶部或者底部阴影颜色的ContextWrapper
 */
public class ContextWrapperEdgeEffect extends ContextWrapper {

    public static final String TAG = ContextWrapperEdgeEffect.class.getSimpleName();

    private ResourcesEdgeEffect mResourcesEdgeEffect;
    private int mColor;
    private Drawable mEdgeDrawable;
    private Drawable mGlowDrawable;

    public ContextWrapperEdgeEffect(Context context) {
        this(context, 0);
    }

    public ContextWrapperEdgeEffect(Context context, int color) {
        super(context);
        mColor = color;
        Resources resources = context.getResources();
        mResourcesEdgeEffect = new ResourcesEdgeEffect(resources.getAssets(), resources.getDisplayMetrics(), resources.getConfiguration());
    }

    public void setEdgeEffectColor(int color) {
        mColor = color;
        if (mEdgeDrawable != null) mEdgeDrawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
        if (mGlowDrawable != null) mGlowDrawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
    }

    @Override
    public Resources getResources() {
        return mResourcesEdgeEffect;
    }

    private class ResourcesEdgeEffect extends Resources {
        private int overscroll_edge = getPlatformDrawableId("overscroll_edge");
        private int overscroll_glow = getPlatformDrawableId("overscroll_glow");

        public ResourcesEdgeEffect(AssetManager assets, DisplayMetrics metrics, Configuration config) {
            //super(metrics, localConfiguration);
            super(assets, metrics, config);
        }

        private int getPlatformDrawableId(String name) {
            try {
                int i = ((Integer) Class.forName("com.android.internal.R$drawable").getField(name).get(null)).intValue();
                return i;
            } catch (ClassNotFoundException e) {
                Log.e(TAG, "Cannot find internal resource class");
                return 0;
            } catch (NoSuchFieldException e1) {
                Log.e(TAG, "Internal resource id does not exist: " + name);
                return 0;
            } catch (IllegalArgumentException e2) {
                Log.e(TAG, "Cannot access internal resource id: " + name);
                return 0;
            } catch (IllegalAccessException e3) {
                Log.e(TAG, "Cannot access internal resource id: " + name);
            }
            return 0;
        }

        @Override
        public Drawable getDrawable(int resId) throws Resources.NotFoundException {
            Drawable ret = null;
            if (resId == this.overscroll_edge) {
                mEdgeDrawable = ContextWrapperEdgeEffect.this.getBaseContext().getResources().getDrawable(R.drawable.community_overscroll_edge);
                ret = mEdgeDrawable;
            } else if (resId == this.overscroll_glow) {
                mGlowDrawable = ContextWrapperEdgeEffect.this.getBaseContext().getResources().getDrawable(R.drawable.community_overscroll_glow);
                ret = mGlowDrawable;
            } else return super.getDrawable(resId);

            if (ret != null) {
                ret.setColorFilter(mColor, PorterDuff.Mode.MULTIPLY);
            }

            return ret;
        }
    }
}

上面仅仅是ScrollView的示例,其他可滚动的View同样可以使用ContextWrapperEdgeEffect进行修改边缘颜色。

4.适配高低版本

  因为5.0以上版本ScrollView的acEdgeGlowTop和acEdgeGlowBottom是私有访问权限,所以要通过反射机制调用setColor方法。

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();
        }
    } else {
        mScrollView.setEdgeEffectColor(Color.YELLOW);
    }
}

  至此,就可以完成对可滑动View滑动到顶部或者底部出现的边缘效果的颜色进行修改了。

    原文作者:studenthc
    原文地址: https://www.jianshu.com/p/bd00def3db36
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞