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.
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));
}
}