Android: Change Shape Color in Runtime

Android: Change Shape Color in runtime

See if something similar to this works for you:

TextView tv2 = (TextView) rl.findViewById(R.id.toggle_indicator);
/* Refer to http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html#mutate()
to understand why we need to mutate the GradientDrawable*/
GradientDrawable sd = (GradientDrawable) tv2.getBackground().mutate();
sd.setColor(0xff999999);
sd.invalidateSelf();

In my case I have a TextView which has a ShapeDrawable as a background. I wanted to change its color and managed to make this work. Inexplicably, tv2.getBackground() returns a GradientDrawable instead of a ShapeDrawable -- this has been reported elsewhere as well.

Edit: About the color, try setting an alpha value of 0xff. If you notice, even in my code above the setColor() function takes an extra hex value apart from the regular RGB hex value. This is for Alpha/Opacity. If this is set to 0x00 the Drawable will have a black color, irrespective of the RGB (assuming that your background color is black). 0x00 is a completely transparent object & 0xff is a completely opaque object.

How can I change shape color programmatically?

this one work for me and gave me round shape with color

 ShapeDrawable biggerCircle= new ShapeDrawable( new OvalShape());
biggerCircle.setIntrinsicHeight( 60 );
biggerCircle.setIntrinsicWidth( 60);
biggerCircle.setBounds(new Rect(30, 30, 30, 30));
biggerCircle.getPaint().setColor(Color.parseColor(first));//you can give any color here
holder.firstcolor.setBackgroundDrawable(biggerCircle);

changing shape color programmatically in android

Change the code as below

GradientDrawable bgShape = (GradientDrawable)btn_ColorPick.getBackground();
bgShape.mutate()
bgShape.setColor(Color.RED);

How to change the color of drawable shape in the layout file

You can by setting the same drawable (the one you provided) to all the buttons, then in your code:

Example:

Drawable mDrawable = ContextCompat.getDrawable(context, R.drawable.yourDrawable); 
mDrawable.setColorFilter(new PorterDuffColorFilter(yourColorInt,PorterDuff.Mode.MULTIPLY));

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
yourButton.setBackgroundDrawable(mDrawable);
} else {
yourButton.setBackground(mDrawable);
}

Do this for each of your buttons, but remember to replace yourColorInt with the color you want for the button you're applying it to.

How to change shape color dynamically?

You could modify it simply like this

GradientDrawable bgShape = (GradientDrawable)btn.getBackground();
bgShape.setColor(Color.BLACK);


Related Topics



Leave a reply



Submit