How to add button tint programmatically - android

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)

Related

TextInputLayout with loading indicator

Using TextInputLayout from Material Design library we can use various end icon modes for password redaction, text clearing and custom mode. Furthermore, if we use any of Widget.MaterialComponents.TextInputLayout.*.ExposedDropdownMenu styles it will automatically apply special end icon mode that displays open and close chevrons.
Example of various icon modes:
Given the variety of use cases for the end icon, we decided to use a loading indicator in the InputTextLayout so that it looks like this:
How should one proceed to implement it?
One can simply set use custom drawable in place of End Icon like this:
textInputLayout.endIconMode = TextInputLayout.END_ICON_CUSTOM
textInputLayout.endIconDrawable = progressDrawable
The problematic part is getting hold of a loading indicator drawable.
Bad Option 1
There is no public drawable resource we can use for a loading indicator.
There is android.R.drawable.progress_medium_material but it is marked private and cannot be resolved in code. Copying the resource and all of its dependent private resources totals into about 6 files (2 drawables + 2 animators + 2 interpolators). That could work but feels quite like a hack.
Bad Option 2
We can use ProgressBar to retrieve its indeterminateDrawable. The problem with this approach is that the drawable is closely tied to the ProgressBar. The indicator is animated only when the ProgressBar is visible, tinting one View will also tint the indicator in the other View and probably additional weird behavior.
In similar situations, we can use Drawable.mutate() to get a new copy of the drawable. Unfortunately the indeterminateDrawable is already mutated and thus mutate() does nothing.
What actually worked to decouple the drawable from the ProgressBar was a call to indeterminateDrawable.constantState.newDrawable(). See documentation for more insight.
Anyway, this still feels like a hack.
Good Option 3
Although the drawable resource is marked private we can resolve certain theme attributes to get the system's default loading indicator drawable. The theme defines progressBarStyle attribute that references style for ProgressBar. Inside of this style is indeterminateDrawable attribute that references themed drawable. In code we can resolve the drawable like this:
fun Context.getProgressBarDrawable(): Drawable {
val value = TypedValue()
theme.resolveAttribute(android.R.attr.progressBarStyleSmall, value, false)
val progressBarStyle = value.data
val attributes = intArrayOf(android.R.attr.indeterminateDrawable)
val array = obtainStyledAttributes(progressBarStyle, attributes)
val drawable = array.getDrawableOrThrow(0)
array.recycle()
return drawable
}
Great, now we have a native loading indicator drawable without hacks!
Extra measures
Animation
Now if you plug in the drawable into this code
textInputLayout.endIconMode = TextInputLayout.END_ICON_CUSTOM
textInputLayout.endIconDrawable = progressDrawable
you will find out that it does not display anything.
Actually, it does display the drawable correctly but the real problem is that it is not being animated. It just happens that at the beginning of the animation the drawable is collapsed into an invisible point.
Unfortunately for us, we cannot convert the drawable to its real type AnimationScaleListDrawable because it is in com.android.internal.graphics.drawable package.
Fortunately for us, we can type it as Animatable and start() it:
(drawable as? Animatable)?.start()
Colors
Another unexpected behavior happens when TextInputLayout receives/loses focus. At such moments it will tint the drawable according to colors defined by layout.setEndIconTintList(). If you don't explicitly specify a tint list, it will tint the drawable to ?colorPrimary. But at the moment when we set the drawable, it is still tinted to ?colorAccent and at a seemingly random moment it will change color.
For that reason I recommend to tint both layout.endIconTintList and drawable.tintList with the same ColorStateList. Such as:
fun Context.fetchPrimaryColor(): Int {
val array = obtainStyledAttributes(intArrayOf(android.R.attr.colorPrimary))
val color = array.getColorOrThrow(0)
array.recycle()
return color
}
...
val states = ColorStateList(arrayOf(intArrayOf()), intArrayOf(fetchPrimaryColor()))
layout.setEndIconTintList(states)
drawable.setTintList(states)
Ultimately we get something like this:
with android.R.attr.progressBarStyle (medium) and android.R.attr.progressBarStyleSmall respectively.
You can use the ProgressIndicator provided by the Material Components Library.
In your layout just use:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textinputlayout"
...>
<com.google.android.material.textfield.TextInputEditText
.../>
</com.google.android.material.textfield.TextInputLayout>
Then define the ProgressIndicator using:
ProgressIndicatorSpec progressIndicatorSpec = new ProgressIndicatorSpec();
progressIndicatorSpec.loadFromAttributes(
this,
null,
R.style.Widget_MaterialComponents_ProgressIndicator_Circular_Indeterminate);
progressIndicatorSpec.circularInset = 0; // Inset
progressIndicatorSpec.circularRadius =
(int) dpToPx(this, 10); // Circular radius is 10 dp.
IndeterminateDrawable progressIndicatorDrawable =
new IndeterminateDrawable(
this,
progressIndicatorSpec,
new CircularDrawingDelegate(),
new CircularIndeterminateAnimatorDelegate());
Finally apply the drawable to the TextInputLayout:
textInputLayout.setEndIconMode(TextInputLayout.END_ICON_CUSTOM);
textInputLayout.setEndIconDrawable(progressIndicatorDrawable);
It is the util method to convert to dp:
public static float dpToPx(#NonNull Context context, #Dimension(unit = Dimension.DP) int dp) {
Resources r = context.getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
You can easily customize the circularRadius and the indicatorColors and all other attributes defined in the ProgressIndicator:
progressIndicatorSpec.indicatorColors = getResources().getIntArray(R.array.progress_colors);
progressIndicatorSpec.growMode = GROW_MODE_OUTGOING;
with this array:
<integer-array name="progress_colors">
<item>#color/...</item>
<item>#color/....</item>
<item>#color/....</item>
</integer-array>
Note: it requires at least the version 1.3.0-alpha02.
This question already has a good answer, however, I would like to post a more concise and simpler solution. If you use androidx you have a class that inherits Drawable - CircularProgressDrawable, so you can use it. This some piece of code I use in my project:
CircularProgressDrawable drawable = new CircularProgressDrawable(requireContext());
drawable.setStyle(CircularProgressDrawable.DEFAULT);
drawable.setColorSchemeColors(Color.GREEN);
inputLayout.setEndIconOnClickListener(view -> {
inputLayout.setEndIconDrawable(drawable);
drawable.start();
//some long running operation starts...
}
Result:

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.

Programmatically changing underline color of EditText

I have an ordinary EditText field that I would like to programmatically change the underline color for.
<EditText
android:id="#+id/edit_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
Other answers suggest changing the background color filter like so:
editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
However, I don't see any change when I run the app. Changing the background itself:
editText.setBackground(color)
changes the entire EditText to color - not what I want!
How do I programmatically change the underline color for an EditText, AppCompatEditText or TextInputEditText? I am using version 25.0.1 of the Support Library.
#degs's answer is correct. But just add one little note: the AppCompatEditText#setSupportBackgroundTintList is now annotated with #RestrictTo(LIBRARY_GROUP) which means:
Restrict usage to code within the same group of libraries
Instead use ViewCompat#setBackgroundTintList. So in your example, it should look like this:
ColorStateList colorStateList = ColorStateList.valueOf(color);
ViewCompat.setBackgroundTintList(editText, colorStateList);
You need to set the backgroundTintList (or supportBackgroundTintList) on the EditText to an instance of ColorStateList containing only the color you wish to change the tint to. An easy way to do this in a backwards-compatible way looks like this:
ColorStateList colorStateList = ColorStateList.valueOf(color);
editText.setSupportBackgroundTintList(colorStateList);
This will give the EditText the desired underline color.
Changing the color of EditText underline programmatically can be done using ColorFilter class and other ways but you will have an API level problem. The best way to resolve these type of issues is by using a 9-Patch image.
https://romannurik.github.io/AndroidAssetStudio/nine-patches.html
go here download a set of drawables and put them in your drawable folder and change the background of EditText programmatically( et_joker.setBackground(your_drawable);
) This will work irrespective to API levels.
I couldn't make it working with the above solution when the edit text is in focus.
I had to add colorControlActivated in the theme.
<style name="StyledTilEditTextTheme">
<item name="colorControlNormal">#color/greyLight</item>
<item name="colorControlActivated">#color/gray_ccc</item>
</style>
This worked for me

android set button background programmatically

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)

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