android set button background programmatically - android

I would like to know how to set the button color programatically?
I have coded the following but fails:
Button11.setBackgroundColor(R.color.red);
Thanks!!

R.color.red is an ID (which is also an int), but is not a color.
Use one of the following instead:
// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not:
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));
Or, alternatively:
Button11.setBackgroundColor(Color.RED); // From android.graphics.Color
Or, for more pro skills:
Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB

Old thread, but learned something new, hope this might help someone.
If you want to change the background color but retain other styles, then below might help.
button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

The answer you're looking for in 2020 and beyond:
setColorFilter(color, mode) is deprecated since API 29 (as discussed here)
button.setBackgroundColor(color) messes with the button style
Now the proper way to set a buttons color is using BlendModeColorFilter() (see documentation).
Usage:
btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
If you work with older APIs too:
fun setButtonColor(btn: Button, color: Int) {
if (Build.VERSION.SDK_INT >= 29)
btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
else
btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}
Please vote to help others finding this answer - it took me quite a while figuring this out ^^

You can set your desired color to the button programmatically like:
Button11.setBackgroundColor(Android.Graphics.Color.parseColor("#738b28"));
Also you can give the text color for a button like:
Button11.setTextColor(Android.Graphics.Color.parseColor("#FFFFFF"));

I have found that Android Studio gives me a warning that getColor() is deprecated when trying to do this:
Button11.setBackgroundColor(getResources().getColor(R.color.red))
So I found doing the method below to be the simple, up-to-date solution:
Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))
You want to avoid hard-coding in the color argument, as it is considered bad code style.
Edit: After using setBackgroundColor() with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.
Source:
https://stackoverflow.com/a/32202256/6030520

For not changing the size of button on setting the background color:
button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
this didn't change the size of the button and works with the old android versions too.

Using setBackgroundColor() affects the style.
So, declare a new style of the same properties with respect to the previous button, with a a different color.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#color/green"/>
<corners android:radius="10dp"/>
</shape>
Now, use OnClick method.
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
location.setBackgroundResource(R.drawable.green);
}
});
this changes the button but looks similar to changing the background.

Further from #finnmglas, the Java answer as of 2021 is:
if (Build.VERSION.SDK_INT >= 29)
btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
else
btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

button.setBackgroundColor(getResources().getColor(R.color.red);
Sets the background color for this view.
Parameters: color the color of the background
R.color.red is a reference generated at the compilation in gen.

You can use the below code for the button color without getting effected the style if used any
yourbtnid.background.setColorFilter(ContextCompat.getColor(context, yourcolor), PorterDuff.Mode.SRC)

Related

Changing BackgroundTint of a MaterialButton

I'm using the lasted support design : 28, alpha3.
I use using the "Theme.MaterialComponents.Light.NoActionBar" as the theme for my application and "MaterialButton" instead of a normal "Button" in my layouts.
I can set the BackgroundTind from the XML as normal but i can't change it via java.
I tried:
deliverSwitch.setBackgroundTintList(getResources().getColorStateList(R.color.colorYellow));
deliverSwitch.setSupportBackgroundTintList(getResources().getColorStateList(R.color.colorYellow));
but none of them worked... I also tried to clear the current tint by leaving the setBackgroundTintList null and it doesn't work either.
I couldn't get it working either. As a workaround I did the following: First you get the current background Drawable, then you tint it with the desired color and set the new background with setBackgroundDrawable for your Material Button.
Drawable background = materialButton.getBackground();
background.setTint(ContextCompat.getColor(getContext(), R.color.bg_button_primary));
materialButton.setBackgroundDrawable(background);
I hope that helps.

How to add button tint programmatically

In the new AppCompat library, we can tint the button this way:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/follow"
android:id="#+id/button_follow"
android:backgroundTint="#color/blue_100"
/>
How can I set the tint of the button programmatically in my code?
I'm basically trying to implement a conditional coloring of the button based on some user input.
According to the documentation the related method to android:backgroundTint is setBackgroundTintList(ColorStateList list)
Update
Follow this link to know how create a Color State List Resource.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="#your_color_here" />
</selector>
then load it using
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
where contextInstance is an instance of a Context
using AppCompart
btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
You could use
button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.blue_100)));
But I would recommend you to use a support library drawable tinting which just got released yesterday:
Drawable drawable = ...;
// Wrap the drawable so that future tinting calls work
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);
// We can now set a tint
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);
You can find more in this blog post (see section "Drawable tinting")
Seems like views have own mechanics for tint management, so better will be put tint list:
ViewCompat.setBackgroundTintList(
editText,
ColorStateList.valueOf(errorColor));
here's how to do it in kotlin:
view.background.setTint(ContextCompat.getColor(context, textColor))
In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:
Drawable buttonDrawable = button.getBackground();
buttonDrawable = DrawableCompat.wrap(buttonDrawable);
//the color is a direct color int and not a color resource
DrawableCompat.setTint(buttonDrawable, Color.RED);
button.setBackground(buttonDrawable);
This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.
The simple way to do it
in Java
myButton.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.white)));
in Kotlin
myButton.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.white)))
Have you tried something like this?
button.setBackgroundTintList(getResources().getColorStateList(R.id.blue_100));
note that getResources() will only work in an activity. But it can be called on every context too.
this is easily handled in the new Material Button from material design library, first, add the dependency:
implementation 'com.google.android.material:material:1.1.0-alpha07'
then in your XML, use this for your button:
<com.google.android.material.button.MaterialButton
android:id="#+id/accept"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/i_accept"
android:textSize="18sp"
app:backgroundTint="#color/grayBackground_500" />
and when you want to change the color, here's the code in Kotlin, It's not deprecated and it can be used prior to Android 21:
accept.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources,
R.color.colorPrimary, theme))
You can use DrawableCompat e.g.
public static Drawable setTint(Drawable drawable, int color) {
final Drawable newDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(newDrawable, color);
return newDrawable;
}
The way I managed to get mine to work was by using CompoundButtonCompat.setButtonTintList(button, colour).
To my understanding this works regardless of android version.
I had a similar problem. I wished to colour a complex drawable background for a view based on a color (int) value.
I succeeded by using the code:
ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{color});
textView.setBackgroundTintList(csl);
Where color is an int value representing the colour required.
This represents the simple xml ColorStateList:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="color here"/>
</selector>
Hope this helps.
If you are using Kotlin and Material Design, you can change color of your MaterialButton like this:
myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))
You can improve it even better by creating an extension function for your MaterialButton in order to make you code more readable and your coding little more convenient:
fun MaterialButton.changeColor(color: Int) {
this.background.setTintList(ContextCompat.getColorStateList(context, color))
}
Then, you can use your function everywhere like this:
myButton.changeColor(R.color.myColor)
You can use something like that:
myButton.backgroundTintList = AppCompatResources.getColorStateList(context, R.color.primary_variant)
For ImageButton you can use:
favoriteImageButton.setColorFilter(Color.argb(255, 255, 255, 255)); // White Tint
The suggested answer here doesn't work properly on android 5.0 if your XML based color state list references themed attributes..
For instance, I have an xml color state list like so:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?colorPrimary" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
Using this as my backgroundTint from xml works just fine on android 5.0 and everything else. However if I try to set this in code like this:
(Don't do this)
myButton.setSupportButtonTintList(ContextCompat.getColorStateList(myButton.getContext(), R.color.btn_tint_primary));
It actually doesn't matter if I pass the Activity or the button's context to ContextCompat.getColorStateList() method, neither will give me the proper color state list with respect to the theme the button is within. This is because using theme attributes in color state lists wasn't supported until api 23 and ContextCompat does not do anything special to resolve these. Instead you must use AppCompatResources.getColorStateList() which does its own resource parsing/theme attribute resolution on devices < API 23.
Instead, you must use this:
myButton.setSupportBackgroundTintList(AppCompatResources.getColorStateList(myButton.getContext(), R.color.btn_tint_primary));
TLDR: use AppCompatResources and not -ContextCompat- if you'll need resolved themed resources across all API versions of android.
For more information on the topic, see this article.
In addition to Shayne3000's answer you can also use a color resource (not only an int color). Kotlin version:
var indicatorViewDrawable = itemHolder.indicatorView.background
indicatorViewDrawable = DrawableCompat.wrap(indicatorViewDrawable)
val color = ResourcesCompat.getColor(context.resources, R.color.AppGreenColor, null) // get your color from resources
DrawableCompat.setTint(indicatorViewDrawable, color)
itemHolder.indicatorView.background = indicatorViewDrawable
There are three options for it using setBackgroundTintList
int myColor = Color.BLACK;
button.setBackgroundTintList(new ColorStateList(EMPTY, new int[] { myColor }));
button.setBackgroundTintList(ColorStateList.valueOf(myColor));
button.setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.my_color));
If you dont want to care about different versions of android, you can use this code, for basicaly any view. Worked for me.
val states = arrayOf(intArrayOf(android.R.attr.state_enabled))
val colors = intArrayOf(Color.GREEN) // your color here
val colorStateList = ColorStateList(states, colors)
ViewCompat.setBackgroundTintList(yourButtonHere,colorStateList)
Kotlin version, wish a nice day to everyone reading this ;)
btw. if you created some drawable background shape this should override only only the tint color.
checkbox.ButtonTintList = ColorStateList.ValueOf(Android.Color.White);
Use ButtonTintList instead of BackgroundTintList
Tint can be added to button like:
filterBtn.setBackgroundTintList(ContextCompat.getColorStateList(context,R.color.colorPrimary))
simple we can also use for an imageview
imageView.setColorFilter(ContextCompat.getColor(context,
R.color.COLOR_YOUR_COLOR));
With Kotlin,
checkbox.buttonTintList = AppCompatResources.getColorStateList(context, color.colorPrimary)

Change thumb color from a seekbar

I have a seekbar and i am trying to change the thumb color. I found two photos that describes what i actually want to do.
I have this seekbar (default) :
and i am trying to change it's color thumb like this.. :
(I know how to change background progress color but not the thumb color)..
seekBar1calling.getProgressDrawable().setColorFilter(Color.WHITE, Mode.SRC_IN);
Is there any way to achieve this using java code? Thanks in advance!!
I just used an online style generator which gave me what i needed
http://android-holo-colors.com/
Just choose the widget and color you want and you are ready! ;)
Just use:
mySeekbar.getThumb().setColorFilter(myColor, PorterDuff.Mode.MULTIPLY);
Edit: method getThumb is only available since API 16+ (Jelly Bean).
The other answers are old and didn't work for me, this did.
seekbar.setThumbTintList(ContextCompat.getColorStateList(this, R.color.disabled));
Here is a quick and easy solution which worked for me as expected. Just implement this code after you initialized the seekbar to avoid NPE's.
You have to define the color itself under res/values/colors.xml
int blue = ContextCompat.getColor(context, R.color.seekbar_blue);
filterSeekBar.getThumb().setColorFilter(blue, PorterDuff.Mode.SRC_ATOP);
filterSeekBar.getProgressDrawable().setColorFilter(blue, PorterDuff.Mode.SRC_ATOP);
That's all!
Note: The color of the Progress-Background is not as dark as the Button / Thumb itself.
If you want to know more about the PorfuerDuff part check this answer on Stackoverflow:
Phasmal & Lee's answer to PorfuerDuff modes

How to reset a button's background color to default?

I read a couple of posts but none of them had the working solution.
Once you do
button.setBackgroundColor(0x00000000);
How do you revert the button's background color back to default color?
use:
btn.setBackgroundResource(android.R.drawable.btn_default);
If the background color was set using
btn.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
it can be reset using:
btn.getBackground().clearColorFilter();
In contrast to button.setBackgroundColor() setting the color this way preserves the button's shape.
Nobody mentioned TRANSPARENT
use it like this
findViewById(R.id.button_id).setBackgroundColor(Color.TRANSPARENT);
Thank me later
this worked better for me :
Button defbtn=new Button(this);
btn.setBackground(defbtn.getBackground());

How to set background color of a View

I'm trying to set the background color of a View (in this case a Button).
I use this code:
// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();
It causes the Button to disappear from the screen. What am I doing wrong, and what is the correct way to change the background color on any View?
Thanks.
You made your button transparent. The first byte is the alpha.
Try v.setBackgroundColor(0xFF00FF00);
When you call setBackgoundColor it overwrites/removes any existing background resource, including any borders, corners, padding, etc.
What you want to do is change the color of the existing background resource...
View v;
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
Experiment with PorterDuff.Mode.* for different effects.
Several choices to do this...
Set background to green:
v.setBackgroundColor(0x00FF00);
Set background to green with Alpha:
v.setBackgroundColor(0xFF00FF00);
Set background to green with Color.GREEN constant:
v.setBackgroundColor(Color.GREEN);
Set background to green defining in Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myGreen">#00FF00</color>
<color name="myGreenWithAlpha">#FF00FF00</color>
</resources>
and using:
v.setBackgroundResource(R.color.myGreen);
and:
v.setBackgroundResource(R.color.myGreenWithAlpha);
or the longer winded:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));
and:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));
You can set the hex-color to any resource with:
View.setBackgroundColor(Color.parseColor("#e7eecc"));
// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();
The code does not set the button to green. Instead, it makes the button totally invisible.
Explanation: the hex value of the color is wrong. With an Alpha value of zero, the color will be invisible.
The correct hex value is 0xFF00FF00 for full opacity green. Any Alpha value between 00 and FF would cause transparency.
For setting the first color to be seen on screen, you can also do it in the relevant layout.xml (better design) by adding this property to the relevant View:
android:background="#FF00FF00"
and what is the correct way to change
the background color on any View?
On any View? What you have is correct, though you should drop the invalidate() call.
However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.
In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.
try to add:
setBackgroundColor(Color.parseColor("#FF0000"));
I use at API min 16 , target 23
Button WeekDoneButton = (Button) viewWeeklyTimetable.findViewById(R.id.week_done_button);
WeekDoneButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
mButton.setBackgroundColor(getResources().getColor(R.color.myColor));
You can simple use :
view.setBackgroundColor(Color.parseColor("#FFFFFF"));
You can simple use :
view.setBackgroundColor(Color.rgb(0, 198, 255));
This question talks about changing the background color of a view. In one of the answers, the person explains how to change the background color during runtime. Obviously you are going to look into how to modify other objects on the screen, but this should give you a good start by at least allowing you to modify the background color of the view on button click.
Stating with Android 6 use ContextCompact
view.setBackgroundColor( ContextCompat.getColor(this, R.color.your_color));
This works for me
v.getBackground().setTint(Color.parseColor("#212121"));
That way only changes the color of the background without change the background itself. This is usefull for example if you have a background with rounded corners.
In kotlin you could do it like this:
val backgroundColor = R.color.whatever_color_you_like
view.setBackgroundColor(getColorCompat(backgroundColor))
Where getColorCompat() is an extension function:
/**
* Extension method to provide simpler access to {#link ContextCompat#getColor(int)}.
*/
fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)
view.setBackgroundColor(R.color.primaryColor);
Adds color to previous color value, so i have a different color.
What works for me is :
view.setBackgroundResource(R.color.primaryColor);
Let suppose we have a primary color in values=>colors.xml as:
<resources>
<color name="primary">#FDD835</color>
</resources>
so if we want to use our custom color into setBackgroundColor(#ColorInt int Color) then we just need an annotation #SuppressLint("ResourceAsColor") with constructor/method which will be used as:
#SuppressLint("ResourceAsColor")
public _LinearLayout(Context context) {
super(context);
// Formatting our layout : )
super.setBackgroundColor(R.color.primary);
....
}
You must pass an int in the argument.
First Example:
view.setBackgroundColor(-500136)
Second Example:
int colorId = R.color.green;
view.setBackgroundResource(colorId);
This should work fine: v.setBackgroundColor(0xFF00FF00);
I tried all the above ways. But I havent achieve what i need. Here is my try.
If you are using hexcode for color and want to set the color as background of image, then this is the kotlin code.
val bitmap = Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val colorCode = "#ffffff"
canvas.drawColor(Color.parseColor(colorCode))
mImageViewLogo.setImageBitmap(bitmap)
When calling setBackgroundColor on a view you need to set the alpha value to a non-zero value (e.g. 0xFF), otherwise the color will not show up.
TextView tv = (TextView)findViewById(R.id.myTextview);
int rgb = 0xF05922; // Orange
tv.setBackgroundColor(0xFF000000|rgb); // Use bitwise OR to add alpha to RGB value

Categories

Resources