I want to use a code that indicates the color of the button (id=button1) and do something if the color is blue,
I mean =
if the color of button1 is blue type 1, if its green,yellow or other color, type game over.
how can i do it?
i tried this way:
if(v.getId() == R.id.button1){
ColorDrawable buttonColor = (ColorDrawable) button1.getBackground();
int colorId = buttonColor.getColor();
}
there is an error:
Multiple markers at this line
- Type mismatch: cannot convert from ColorDrawable to int
- The method getColor() is undefined for the type
and if you are hovering over the getColor() you get another error:
The method getColor() is undefined for the type ColorDrawable
what can I do?
thx.
This is the wrong way to do it. You should never use UI attributes to determine program state, doing so leads to spaghetti code. Instead, you should have some variable in your code with a name that means something easily understood that tracks the state of the button. Whenever you change the color of the button, you set this variable. Then when you need to make some decision based on the color, you use this variable.
You can also try something like set the color value as the tag like
android:tag="#ff0000"
And access it from the code
String colorCode = (String)btn.getTag();
OR
Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();
Related
I have a custom layout that has custom attributes, one of them being a color. I have users set this attribute to a color (not a common color) and I use TypedArray's getColor method to retrieve this color and set it to an integer (if I print this int out, it is negative). Let's say I do something like this:
int myColor;
TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, 0, 0);
myColor = ta.getColor(R.styleable.MyView_myColor, -1);
if (myColor == R.color.special_shade_of_yellow) {
mySpecialMethod()
}
Now let's say a user sets the attribute to be R.color.special_shade_of_yellow. However, the if block never goes through so mySpecialMethod() never gets called. For some reason, myColor is a negative value, while R.color.special_shade_of_yellow isn't. Why aren't they returning the same values? Thanks!
Colors in Android can be slightly confusing. You have color resource identifiers (like R.color.my_color) and you have color values (like 0xff0000), but both are represented by an int value.
TypedArray.getColor() will return a color value, i.e. a real color that you can directly apply to a view. Therefore, it's not something you'll want to compare to R.color.special_shade_of_yellow with a simple ==.
Try this instead:
if (myColor == ContextCompat.getColor(getContext(), R.color.special_shade_of_yellow)) {
...
}
ContextCompat.getColor() will resolve your color resource identifier (here R.color.special_shade_of_yellow) to a color value, and then you can perform an == comparison.
How do you get the actual value of a referenced color. In a layout I can use the following...
android:textColor="?android:attr/colorAccent"
..and this works in setting the text color of a TextView to the theme defined accent color. How do I get the value of the colorAccent using code at runtime?
Also, how do you discover a list of all the available values, there must be a long list of available colors I could get hold of, but where is that list defined?
If the resource is an Android defined one:
var id = Android.Resource.Attribute.ColorAccent;
If the resource is within a Dialog, Widget, etc.. that is not an Android system resource (i.e. to obtain a DatePickerDialog resource)
var id = SomeDatePickerDialog.Resources.GetIdentifier("date_picker_header_date", "id", "android");
Using the id obtained:
var typedArray = Theme.ObtainStyledAttributes(new int[] { id });
var color = typedArray.GetColor(0, int.MaxValue);
if (color != int.MaxValue)
{
Log.Debug("COLOR", color.ToString());
}
The R list changes with API/Theme, for the base values available:
Colors: https://developer.android.com/reference/android/R.color.html
Styles: https://developer.android.com/reference/android/R.style.html
etc...
But for a complete reference you have to use the Android source for the API the you are looking at:
https://android.googlesource.com/platform/frameworks/base/
So the colors that are defined in the Oreo beta:
https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r4/core/res/res/color/
Then look within the specific color xml file for the how it is defined and use that definition to find the actual value of it (in one on the valueXXX files....)
For the example you have you can get that value with something like this:
//default color instead the attribute is not set.
var color = Color.Blue;
var attributes = new int[] { Android.Resource.Attribute.ColorAccent };
var typeArray = ObtainStyledAttributes(attributes);
//get the fist item (we are sending only one) and passing
//the default value we want, just in case.
var colorAccent = typeArray.GetColor(0, color);
colorAccent will have the Color set in your Theme for the ColorAccent attribute if any or the default value .
Important to mention that this method ObtainStyledAttributes is part of a Context so if you are already in an Activity you will find it as part of it but if you are in any other class you will need to pass in the context in case it's not available.
For the full list of available values you can get it from the Android.Resource.Attribute class. In VS do an inspection to see the different properties this class has. Maybe Android documentation has a better way though.
Hope this helps.-
I want to change background after clicking Button
var bm : Button = messeg
bm . setOnClickListener {
bm . background = R.color.green
}
Error Log:
Error:(35, 31) Type mismatch: inferred type is Int but Drawable! was
expected Error:Execution failed for task ':app:compileDebugKotlin'.
Compilation error. See log for more details
background requires a Drawable, but you are passing a color resource.
You can use setBackgroundColor to set a color resource:
bm.setBackgroundColor(R.color.green)
setBackgroundResource can be used to set a drawable resource:
bm.setBackgroundResource(R.drawable.green_resource)
background property can be used to set a drawable:
bm.background = ContextCompat.getDrawable(context, R.drawable.green_resource)
The current accepted answer is wrong for setBackgroundColor(). In the given example, you set the color to the resource id, but you must pass the color directly.
This won't fail because both values are int, but you'll get weird colors.
Instead of that, you should retrieve first the color from the resource, then set it as background. Example :
val colorValue = ContextCompat.getColor(context, R.color.green)
bm.setBackgroundColor(colorValue)
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
int color = ContextCompat.getColor(getContext(), mColorResourceId);
linearLayout.setBackgroundColor(color);
i have these line of code :
mColorResourceId it's hold R.color.category_numbers -> mColorResourceId = R.color.category_numbers
when i pass mColorResourceId directly to setBackgroundColor(mColorResourceId); it's doesn't change the color despite the method accept int value .
my question why i need this extra step int color = ContextCompat.getColor(getContext(), mColorResourceId); to change the color ??
The setBackgroundColor() method accepts an int that is supposed to be a color value in aarrggbb format. The resource ID R.color.category_numbers is also an int, but it is not a color value; instead it is the identifier of a color resource. Calling ContextCompat.getColor(getContext(), mColorResourceId) retrieves the actual color value corresponding to mColorResourceId.
Part of the reason Android does this kind of indirection is to provide flexibility. The actual color returned may depend on the current theme or the device configuration and may actually change at run time (depending on how you declare your color resource).
Color color = new Color(context.getResources().getColor(R.color.bus_departures_hover));
As seen, I am attemping to create a Color object from a resource. This ain't working though!
What has worked for me is:
Color c = new Color(ContextCompat.getColor(context, R.color.yourColor));
Kotlin way (API REQUIRED 26);
Color.valueOf(ContextCompat.getColor(context, R.color.color_white))
It seems there's no API constructor that receives an int http://developer.android.com/reference/android/graphics/Color.html#Color()
You may use
int color= getResources().getColor(R.color.bus_departures_hover);
And use the color value in a setter.