TextInputLayout with loading indicator - android

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:

Related

Color set by setColorFilter disappears on prelollipop devices

I have a TabLayout which has icons. The idea is to change the colors runtime.
I have and xml drawable file with states: state_pressed, state_selected and default with the same white picture so I can put color later.
I take the drawables for different states:
Drawable[] drawables = stateListDrawable.getConstantState();
and the for every drawable state I put color from another array:
drawables[i].setColorFilter(colors[i], PorterDuff.Mode.MULTIPLY);
The issue is that the color is visible in the beginning, but when I start to click on the icons all the icons becomes white again and I lose the tint.
Everything is working as expected on lollipop and above.
Use the tint method from the v4 Support library
drawables[i] = DrawableCompat.wrap(drawables[i])
DrawableCompat.setTint(drawables[i], colors[i])
I have found my solution, which does not look clean at all, but at least it is working :)
I have created CustomStateListDrawable which extends from StateListDrawable and added the drawables for the different states. Then I have overridden all the methods in the class to see which ones are called and tried to change the colors there. The called late enough(my changes will not be overridden after I make them) was getState(). I have created also a ColorStateList object to hold my colors so the code will look like this:
private ColorStateList colorStateList;
public int[] getState() {
if (colorStateList != null) {
// Resolve the color for the current state
int color = colorStateList.getColorForState(super.getState(), 0);
// Get the current drawable and changed its color.
if (getCurrent() != null) {
getCurrent().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
}
return super.getState();
}
Basically every time when there is a change in the state I get the current drawable and change its color.

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)

?android:attr/selectableItemBackground with another existing background

I have a 9patch set as the background of my layout. However I still want to provide touch feedback by using the selectableItemBackground attr.
I've tried using a <layer-list> with the 9patch and selectableItemBackground as the android:drawable of the second <item>, however that did not work.
I could also try making a selector and overlay the gradient drawable android uses for selectableItemBackground in list_selector_background_pressed.xml with a <layer-list>. But in 4.4 KitKat the selected background color is actually gray instead of blue in JellyBeans, so I can't really hardcode it :(
There has to be an easier way, right guys? D:
I've tried using a with the 9patch and
selectableItemBackground as the android:drawable of the second ,
however that did not work.
Yes, drawable attribute in a layer-list (or state-list) does not accept an attr value. You would see a Resource.NotFoundException. A look at LayerDrawable's (or StateListDrawable's) source code explains why: the value that you provide is assumed to be a drawable's id.
But, you can retrieve a theme and platform-specific drawable for an attribute in code:
// Attribute array
int[] attrs = new int[] { android.R.attr.selectableItemBackground };
TypedArray a = getTheme().obtainStyledAttributes(attrs);
// Drawable held by attribute 'selectableItemBackground' is at index '0'
Drawable d = a.getDrawable(0);
a.recycle();
Now, you can create a LayerDrawable:
LayerDrawable ld = new LayerDrawable(new Drawable[] {
// Nine Path Drawable
getResources().getDrawable(R.drawable.Your_Nine_Path),
// Drawable from attribute
d });
// Set the background to 'ld'
yourLayoutContainer.setBackground(ld);
You'll also need to set yourLayoutContainer's clickable attribute:
android:clickable="true"

What is default color for text in textview?

I set the color to red , and after that I want to set the color again back to default, but I do not know what is default color, does anyone knows ?
Actually the color TextView is:
android:textColor="#android:color/tab_indicator_text"
or
#808080
You can save old color and then use it to restore the original value. Here is an example:
ColorStateList oldColors = textView.getTextColors(); //save original colors
textView.setTextColor(Color.RED);
....
textView.setTextColor(oldColors);//restore original colors
But in general default TextView text color is determined from current Theme applied to your Activity.
There are some default colors defined in android.R.color
int c = getResources().getColor(android.R.color.primary_text_dark);
Get these values from attributes:
int[] attrs = new int[] { android.R.attr.textColorSecondary };
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, attrs);
DEFAULT_TEXT_COLOR = a.getColor(0, Color.RED);
a.recycle();
There are defaults in the theme that Android uses if you don't specifiy a text color. It may be different colors in various Android UIs (e.g. HTC Sense, Samsung TouchWiz, etc). Android has a _dark and _light theme, so the defaults are different for these (but nearly black in both of them in vanilla android). It is however good practice to define your primary text color yourself for to provide a consistent style throughout the devices.
In code:
getResources().getColor(android.R.color.primary_text_dark);
getResources().getColor(android.R.color.primary_text_light);
In xml:
android:color="#android:color/primary_text_dark"
android:color="#android:color/primary_text_light"
As reference in vanilla Android the dark theme text color is #060001 and the in the light theme it's #060003 since API v1. See the android style class here
I know it is old but according to my own theme editor with default light theme, default
textPrimaryColor = #000000
and
textColorPrimaryDark = #757575
I used a color picker on the textview and got this #757575
It may not be possible in all situations, but why not simply use the value of a different random TextView that exists in the same Activity and that carries the colour you are looking for?
txtOk.setTextColor(txtSomeOtherText.getCurrentTextColor());
The color of text inside a TextView is totally dependent on your theme.
The easiest way to know it:
Add a TextView to any xml file
Select the TextView
Click on Split view
Open the Attributes tab and scroll to the color section.
As you can see, according to my theme it is: #android:color/secondary_text_material_light
I believe the default color integer value is 16711935 (0x00FF00FF).
hey you can try this
ColorStateList colorStateList = textView.getTextColors();
String hexColor = String.format("#%06X", (0xFFFFFF & colorStateList.getDefaultColor()));
I found that android:textColor="#android:color/secondary_text_dark" provides a closer result to the default TextView color than android:textColor="#android:color/tab_indicator_text".
I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using
You could use TextView.setTag/getTag to store original color before making changes. I would suggest to create an unique id resource in ids.xml to differentiate other tags if you have.
before setting to other colors:
if (textView.getTag(R.id.txt_default_color) == null) {
textView.setTag(R.id.txt_default_color, textView.currentTextColor)
}
Changing back:
textView.getTag(R.id.txt_default_color) as? Int then {
textView.setTextColor(this)
}
There are some default colours which get defined in the Themes of app. Below is the code snippet which you can use to get the current default color programmatically.
protected int getDefaultTextColor(){
TextView textView = new TextView(getContext());
return textView.getCurrentTextColor();
}
There is no default color. It means that every device can have own.

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