如何为RecyclerView创建一个发光选择器?

时间:2016-11-29 09:18:51

标签: android android-recyclerview android-drawable glow

我需要让RecyclerView的项目在聚焦时发光。 像这样 Glowing view

9补丁不是一个合适的解决方案,因为具有透明度的图像并不总是正方形。

1 个答案:

答案 0 :(得分:1)

使用此answer中的代码,我创建了一个utils类。

public class GlowEffectUtils {

    @NonNull
    public static Drawable createSelector(@NonNull Resources resources, @NonNull View view) {
        Bitmap glow = createGlow(view);

        StateListDrawable selector = new StateListDrawable();
        BitmapDrawable glowDrawable = new BitmapDrawable(resources, glow);
        selector.addState(new int[]{android.R.attr.state_focused}, glowDrawable);

        return selector;
    }

    @NonNull
    private static Bitmap createGlow(@NonNull View view) {
        int glowRadius = 15;

        int glowColor = Color.rgb(255, 255, 255);

        Bitmap src = createBitmap(view);
        Bitmap alpha = src.extractAlpha();

        Bitmap bmp = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmp);

        Paint paint = new Paint();
        paint.setColor(glowColor);

        paint.setMaskFilter(new BlurMaskFilter(glowRadius, BlurMaskFilter.Blur.OUTER));
        canvas.drawBitmap(alpha, 0, 0, paint);
        return bmp;
    }

    @NonNull
    private static Bitmap createBitmap(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
    }
}

并设置如下:

Resources resources = itemView.getContext().getResources();
Drawable selector = GlowEffectUtils.createSelector(resources, itemView);
itemView.setBackground(selector);