首页 > 解决方案 > set background for itemView programmatically

问题描述

I'm trying to set the background of a ViewHolder Holder.itemView by holder.itemView.setBackground('someKindofDrawable').

I used gradient to create it but it doesn't give the expected result. i need to create a simple lightweight component for the background.

this is the code i use:

GradientDrawable gradientRectangle = new GradientDrawable(
                Orientation.TOP_BOTTOM,
                new int[]{0xFFFFFFFF,0x00000000});

gradientRectangle.setShape(GradientDrawable.RECTANGLE); 

holder.itemView.setBackground(gradientRectangle);

the image is the expected result (the boarders represent the rectangle).

expected result

标签: javaandroiduser-interface

解决方案


我找到了答案(如果它对任何人有帮助):

public class DrawableItemSelectedBackgroundITopColor
{
    LayerDrawable layerdrawable;
    Drawable[] DrawableArray;

    ColorDrawable topColor;
    ColorDrawable bottomColor;

    public DrawableItemSelectedBackgroundITopColor(Context context, String Theme)
    {

        topColor = new ColorDrawable(ContextCompat.getColor(context,R.color.tiny_prints_blue));
        bottomColor = new ColorDrawable(ContextCompat.getColor(context,R.color.white));

        DrawableArray = new Drawable[]{
                topColor,
                bottomColor
        };

        layerdrawable = new LayerDrawable(DrawableArray);

        layerdrawable.setLayerInset(0,0,0,0,0);
        layerdrawable.setLayerInset(1,0,9,0,0);
    }

    public LayerDrawable getDrawableBackgroundItemTop(){
        return layerdrawable;
    }
}

推荐阅读