Change the shape color of a ImageButton

后端 未结 1 1361
离开以前
离开以前 2020-12-12 06:05

I have a recyclerView where I create 12 ImageButtons. As default they are all black colored, because I made a custom shape for the imageButton that have a black solid color.

1条回答
  •  北海茫月
    2020-12-12 06:41

    Your problem is that in your case getBackground() is returning a RippleDrawable, not a GradientDrawable. Both extend Drawable, but you can not cast one to the other. Try this:

    public List initColorButtons(){
        colorButtonList = new ArrayList<>();
    
        //here we retrive all colors from color.xml
        Resources resources = App.getAppContext().getResources();
        String colors[] = resources.getStringArray(R.array.backgroundcolors);
    
        for(int i=0; i

    Result:

    You can read more on how to create a ColorStateList in this SO question.

    EDIT: In order to correctly modify the buttons you create with the method onCreateViewHolder, you need to implement onBindViewHolder in your Adapter and change the color of your buttons there.

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
            Drawable drawable = holder.getBackground();
    
            if (drawable instanceof GradientDrawable) {
                GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
                gd.setColor(Color.parseColor(colors[position]));
            } else if (drawable instanceof RippleDrawable) {
                RippleDrawable rd = (RippleDrawable) drawable;
                int color = Color.parseColor(colors[position]);
                rd.setColor(newColorStateList(color));
            }
    }
    

    0 讨论(0)
提交回复
热议问题