0

I have a button with background set to a drawable to get rounded corners on it. I am trying to get the button to change color on every click without having to make a drawable of every color I want to use.

Currently I am trying to use PorterDuff to apply a color filter over the drawable's white background.

Drawable mDrawable = ResourcesCompat.getDrawable(getResources(),
    R.drawable.rounded_button, null);
mDrawable.setColorFilter(new PorterDuffColorFilter(0x800000ff,
    PorterDuff.Mode.MULTIPLY));

When I load the app, the buttons remain white. Any idea on what I'm doing wrong or a better way to go about this?

Vinnie
  • 13
  • 5
  • Use `Random` method to generate RGB – Rajesh Feb 04 '17 at 06:53
  • @RajeshKushvaha The problem is not how I choose the colors, but how to make them appear on the buttons. Currently I can only get them to change color by editing the drawable xml file directly. The solution I am looking for is how to change the color of the drawable programmatically. – Vinnie Feb 04 '17 at 07:06

2 Answers2

0

Try this

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

Or

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

Or

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

Or

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);

or Use This library https://github.com/TakeoffAndroid/IconColorChanger/blob/master/app/src/main/java/com/takeoffandroid/iconcolorchanger/IconChangerActivity.java

Rajesh
  • 2,618
  • 19
  • 25
0

Please refer this link.You can get some ideas.How to Change color of Button in Android when Clicked?

Community
  • 1
  • 1
Prabha Karan
  • 1,309
  • 3
  • 17
  • 35