Change background colour of view programatically - android

I am trying to change the background colour of my View programatically, using a colour that I defined in my resources. Other SO posts explain to do it like this:
int color = ContextCompat.GetColor(this.context, Resource.Color.my_color_background);
this.myView.SetBackgroundColor(color);
But this doesn't work for me, because SetBackgroundColor takes a Color, not an int... what am I doing wrong here?

I solved it by just creating the Color object myself and setting it with that:
int color = ContextCompat.GetColor(context, Resource.Color.my_color);
this.view.SetBackgroundColor(new Color(color));
Not sure why the constructor is different in Xamarin though...

Related

CardView default background color problematic

The default white background of CardView is problematic or am I missing something? When I fill the CardView with normal unstyled Android UI the white text of TextView is not readable e.g.
Has someone an idea what a good fix for that would be? I use the default "Theme.AppCompat" theme and the other background colors look correct. Is that a missing attribute in the Theme.AppCompat? Or am I doing something wrong? The default colors without setting any values manually should be always working or not?
Edit:
I now apply the default background color for the current style to the cardview like this:
TypedArray array = context.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.colorBackground });
card.setCardBackgroundColor(array.getColor(0, 0xFF00FF));
I think its a quite save "default" fix to have at least no text color problems like in the screenshot but the question remains what should be the best practice here and why the cardview has alsways white as the default background color no matter what theme is used..
By this way you can change Cardview background color,
RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);

How to control the contrast of text?

How do you change the color contrast of text when the background changes? for example If I was to have a black background, black text would not be visible.
This might be helpful: http://developer.android.com/guide/topics/resources/color-list-resource.html
It is a way you can set a color that will change based on certain circumstances.
For example, say you have a TextView that you want to have white text while it is enabled and black text when it is disabled. You can set that up in a xml file using the references in the link above, and then in your xml layout where you define the TextView set the android:textColor to #color/my_text_color. (my_text_color being the xml color list file you created)
Then, as the TextView changes from enabled to disabled (or whatever you end up setting up in the xml file) the color will change automatically as well.
That's one way to do it. However, you might want to try to clarify what you are looking for as it isn't perfectly clear in your question.
Update
After Matt's comment, here is a method you could use to get an inverted color value. There is probably a better way but this should work.
private int getInverseColor(int color){
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255-red, 255-green, 255-blue);
}
You could programmaticly get the color int from a view such as a TextView using one of the getTextColor() methods. You may have to tinker with a Color State List like I linked to above to get the color you want. Then pass that color to the method above to get the inverted color int and set it with one of the setTextColor() methods.

removing backgroundcolor of a view in android

Removing Background color in Android
I have set backgroundColor in code like this,
View.setBackgroundColor(0xFFFF0000);
How to remove this background color on some event?
You should try setting the background color to transparent:
view.setBackgroundColor(0x00000000);
You can use
View.setBackgroundColor(Color.TRANSPARENT);
or
View.setBackgroundColor(0);
or even
View.setBackground(null);
Please remember that almost everything visible on the screen extends View, like a Button, TextView, ImageView, any kind of Layout, so this can be done to almost everything.
Bonus point!
Instead of using View.setBackgroundColor(0xFFFF0000); it is sooooooooo much better to create a color filter with android.graphics.PorterDuff.MULTIPLY option and, if needed, just clear the filter.
Using the color filter, colors look much better because it won't be that "flat" color but a nicer tone of the chosen color.
A light red background would be
View.getBackground().setColorFilter(0x3FFF0000, PorterDuff.Mode.MULTIPLY);
To "remove" the color, just use
View.getBackground().clearColorFilter();
All of the answers about setting color to transparent will work technically. But there are two problems with these approaches:
You'll end up with overdraw.
There is a better way:
If you look at how View.setBackgroundColor(int color) works you'll see a pretty easy solution:
/**
* Sets the background color for this view.
* #param color the color of the background
*/
#RemotableViewMethod
public void setBackgroundColor(#ColorInt int color) {
if (mBackground instanceof ColorDrawable) {
((ColorDrawable) mBackground.mutate()).setColor(color);
computeOpaqueFlags();
mBackgroundResource = 0;
} else {
setBackground(new ColorDrawable(color));
}
}
The color int is just converted to a ColorDrawable and then passed to setBackground(Drawable drawable). So the solution to remove background color is to just null out the background with:
myView.setBackground(null);
View.setBackgroundColor(0); also works. It isn't necessary to put all those zeros.
Choose Any one
View.setBackgroundColor(Color.TRANSPARENT);
or
View.setBackgroundColor(0x00000000);

Android: Create a ColorDrawable object without using xml

Is it possible to create a ColorDrawable object without using xml? I would like to be able to change the backgroundColor of a view programmatically, using setBackgroundColor() or setBackgroundDrawable() or setBackgroundResource(), but I want to be able to specify the RGB values in code, not XML. Is this possible?
I know you can get a View as a Drawable and apply a color filter to it (useful for coloring in Button views) by doing the following:
Drawable d_delete = findViewById(R.id.btn_delete).getBackground();
PorterDuffColorFilter filter_red = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
d_delete.setColorFilter(filter_red);
I know the questions it's a bit old but I've got an easy one. Maybe someone arrive here looking for the answer
View view = findViewById(R.id.view_with_colored_background);
String rgbColor = "#CCFFCC";
view.setBackgroundColor(Color.parseColor(rgbColor));

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