I got the color from the button background and store as a String in the database. Later I want to use this color String in my recyclerView adapter to set the color of my TextView. Below is my code:
#Override
public void onBindViewHolder(NoteListAdapter.NoteListHolder holder, int position) {
current = data.get(position);
final String text = current.getText();
final String get_tag_text = current.getTag();
final String get_tag_color = current.getTag_color();
int[] colors = {Color.parseColor(get_tag_color)};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
holder.note_text.setText(text);
holder.tv_tag_text.setBackground(gd);
holder.tv_tag_text.setText(get_tag_text);
}
The error I got is "Unknown color". The saved color format in the database is (The saved color format is android.graphics.drawable.GradientDrawable#d1790a4)
Below is the code to get the color from a button background drawable file and also my button xml code
color = (GradientDrawable) tag_watchlist.getBackground().mutate();
tag_color= color.toString();
<Button
android:id="#+id/tag_watch"
style="#style/tag_buttons"
android:background="#drawable/watchlist_button"
android:text="Watchlist" />
drawable file code for the button background
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:padding="10dp">
<solid android:color="#a40ce1"/>
<corners android:radius="10dp"/>
</shape>
Can anyone tell me how to resolve this issue??
Edited answer
You are getting exception Caused by: java.lang.IllegalArgumentException: Unknown color mean that you are not passing the color in supported formats to method Color.parseColor.
Make sure you pass the values in following format
#RRGGBB
#AARRGGBB
Here is the valid example
Color.parseColor("#FF4081")
For more information look at documentation Color.parseColor
As per your requirement, you can achieve this API level 24 onward. If you are using current minSdkVersion 24, try below
Change your model class to save color as Integer instead String.
GradientDrawable gradientDrawable = (GradientDrawable) tag_watchlist.getBackground().mutate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
int color = gradientDrawable.getColor().getDefaultColor();
Log.d("TAG","Color is :"+color);
current.setTagColor(color); // where current is your model class
}
To get the color back from model
int color = current.getTagColor();
You need to provide at least two colors for the GradientDrawable the startColor and the endColor
It will probably throw an exception java.lang.IllegalArgumentException: needs >= 2 number of colors with this code:
int[] colors = {Color.parseColor(get_tag_color)};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
Change your code with this:
int[] colors = {Color.parseColor(start_color), Color.parseColor(end_color)};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
If you have get_tag_color for both of your startColor and endColor then replace accordingly but that won't be helpful with GradientDrawable.
Related
I'm trying to set my color for the outline of my button, but I don't get it to work
I'm using material button and when I use
button.setStrokeColorResource(Color.parseColor(#e4dcd4))
is not working and tells me this
Expected a color resource id (R.color.) but received an RGB integer
I tried almost everything I could found about in stack, but I can't get it to set this strokeColor programmatically
Edit
Almost all setColors use #ColorInt , but this strokeColor uses #ColorRes, which is not working for me, also there is setStrokeColor
public void setStrokeColor(#Nullable ColorStateList strokeColor) {
if (isUsingOriginalBackground()) {
materialButtonHelper.setStrokeColor(strokeColor);
}
}
But I can't get it to work either.
It worked like this
val colorInt = Color.parseColor("#e4dcd4")
val csl = ColorStateList.valueOf(colorInt)
my_button.strokeColor = csl
You might try this
button.setStrokeColor(ContextCompat.getColor(this, R.color.your_color_xml));
Other way you can do is
ShapeDrawable gradientDrawable = (ShapeDrawable)button.getBackground();
gradientDrawable.setStroke(2, your_color);
Also as #Gabriele said you can get an int as a color as :
//From RGB
int colorRGB = Color.rgb(255,0,0);
//From HEX String
int colorHEX = Color.parseColor("#FF11AA");
You have to set the width of the stroke because the default value is 0.
<Button
app:strokeWidth="2dp"
../>
button.strokeColor = ColorStateList.valueOf(Color.parseColor("#e4dcd4"))
or
// if color define in color.xml
button.strokeColor = ColorStateList.valueOf(ContextCompat.getColor(this, R.color.yourColorCOde))
// if you have different state and you want to set programmatically then do as :-
var states = arrayOf(
intArrayOf(R.attr.state_enabled),
intArrayOf(-R.attr.state_enabled),
intArrayOf(-R.attr.state_checked),
intArrayOf(R.attr.state_pressed)
)
// Color list define respect of state
var colors = intArrayOf(
Color.BLACK,
Color.RED,
Color.GREEN,
Color.BLUE
)
// Set stroke color
button.strokeColor = ColorStateList(states, colors)
Colour Code : e32b0f, d03559, I want to design its background drawable please help me
Try,
int colors[] = { 0xff255779, 0xfcc6c0cd };
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, colors);
view.setBackgroundDrawable(gradientDrawable);
1. choose color and add color hex code in colors array.
2. GradientDrawable using and set orientation properties.[ex. GradientDrawable.Orientation.TOP_BOTTOM]
3. set view background [ex. Linearlayout.setBackgroundDrawable(gradientDrawable);]
I don't understand why all the colors give the same result. All the textviews background draw in gray, although I have black, white and red. What is the problem here?
<color name="color1">#FFFFFF</color>
<color name="color2">#000000</color>
<color name="color3">#FF0000</color?
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(R.id.color1,R.color.color1);
map.put(R.id.color2,R.color.color2);
map.put(R.id.color3,R.color.color3);
GradientDrawable gradientDrawable;
TextView textView;
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
textView = findTextView(entry.getKey());
gradientDrawable = (GradientDrawable) textView.getBackground().mutate();
gradientDrawable.setColor(entry.getValue());
gradientDrawable.invalidateSelf();
}
Change it to:
gradientDrawable.setColor(getResources().getColor(entry.getValue()));
http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html#setColor(int)
The parameter it takes is:
argb The color used to fill the shape
By passing it the R resource int directly it's basically a random number generated by R. You need to "decode it" into a 0xAARRGGBB colour value using Resources.getColor()
http://developer.android.com/reference/android/content/res/Resources.html#getColor(int)
They probably all look the same because the ints are close to each other in value.
I have a form which I'm dynamically generating from data I receive from a web service. This web service provides images which need to be used in the creation of input elements. I'm having difficuly in setting the progressDrawable of a RatingBar. Though XML I'm able to apply a custom image using the following as the progressDrawable:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+android:id/background" android:drawable="#drawable/custom_star" />
<item android:id="#+android:id/secondaryProgress" android:drawable="#drawable/custom_star" />
<item android:id="#+android:id/progress" android:drawable="#drawable/custom_star" />
</layer-list>
where custom_star is a simple .png image, and with #android:style/Widget.RatingBar as the RatingBar style. This works fine:
but I'm wanting to change custom_star dynamically.
In code, I have tried setting the progress drawable using a bitmap directly:
Drawable d = new BitmapDrawable(getResources(), downloadedImage);
ratingBar.setProgressDrawable(d);
and also by constructing a layer-list:
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {
getResources().getDrawable(R.drawable.custom_star),
getResources().getDrawable(R.drawable.custom_star),
getResources().getDrawable(R.drawable.custom_star)
});
layerDrawable.setId(0, android.R.id.background);
layerDrawable.setId(1, android.R.id.secondaryProgress);
layerDrawable.setId(2, android.R.id.progress);
ratingBar.setProgressDrawable(layerDrawable);
Neither works for me; both result in the custom_star drawable appearing once, stretched by the dimensions of the RatingBar:
Any ideas?
Update:
Luksprog's answer below has made an improvement, but I'm still having a couple of issues. Now, the star drawable is not stretched and the value can be set by touch, but it appears as so with 3/5 selected:
and 5/5 selected:
I believe the scaling of the images can be fixed with a few tweaks, but annoyingly the secondaryProgress drawable doesn't seem to be set - the drawable used for the greyed out not-selected stars. Without that, it's not very usable.
Any ideas?
When using the default progressDrawable or a progressDrawable set through a theme all will be ok as in the constructor for the RatingBar(its superclass ProgressBar to be more precise) widget a method will be called to "make tiles" from that drawable. When using the setProgressDrawable method this doesn't happen and if you pass a simple BitmapDrawable or a LayerDrawable(with simple BitmapDrawables) that Drawable will simply be stretched to cover the widget's background area(what you see know).
In order to make it work you would need to manually do what the RatingBar does at start, create the tiles along with the ClipDrawables that it uses. I've written a method for this, following the source code of the ProgressBar widget:
private Drawable buildRatingBarDrawables(Bitmap[] images) {
final int[] requiredIds = { android.R.id.background,
android.R.id.secondaryProgress, android.R.id.progress };
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
Drawable[] pieces = new Drawable[3];
for (int i = 0; i < 3; i++) {
ShapeDrawable sd = new ShapeDrawable(new RoundRectShape(
roundedCorners, null, null));
BitmapShader bitmapShader = new BitmapShader(images[i],
Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
sd.getPaint().setShader(bitmapShader);
ClipDrawable cd = new ClipDrawable(sd, Gravity.LEFT,
ClipDrawable.HORIZONTAL);
if (i == 0) {
pieces[i] = sd;
} else {
pieces[i] = cd;
}
}
LayerDrawable ld = new LayerDrawable(pieces);
for (int i = 0; i < 3; i++) {
ld.setId(i, requiredIds[i]);
}
return ld;
}
Then you would use the LayerDrawable returned by this method with the setProgressDrawable method. The RatingBar set its width multiplying the width of one of the state bitmaps with the number of stars, so in order to show the right amount of stars this has to be calculated as well.
Your ids are wrong, you have to set
#android:id/background
#android:id/secondaryProgress
#android:id/progress
You can also define a drawable in xml containing your customization
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+android:id/background"
android:drawable="#drawable/star_empty" />
<item android:id="#+android:id/secondaryProgress"
android:drawable="#drawable/star_empty" />
<item android:id="#+android:id/progress"
android:drawable="#drawable/star_full" />
</layer-list>
And you can use setMax on the RatingBar object to set the maximum amount of stars that can be displayed
It's much easier with such solution:
RatingBar ratingBar = new RatingBar(new ContextThemeWrapper(context, R.style.AppTheme_RatingBar), null, 0);
Can a property such as First Color be set using code?
I would like to do something like this:
btnMyButton.drawable = "StatelistDrawable"
btnMyButton.drawable.EnabledDrawable = "GradientDrawable"
btnMyButton.drawable.EnabledDrawable.firstcolor = "255, 199, 199"
btnMyButton.drawable.EnabledDrawable.secondcolor = "255, 79, 79"
If I understand your question correctly you need to create a GradientDrawable as below:
GradientDrawable gradient = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[] {0xFFRRGGBB,0xFFRRGGBB});
gd.setCornerRadius(0f);
Where RRGGBB is the color code in hex (eg 99CC00)
And then set the drawable as the background of your button:
btnMyButton.setBackgroundDrawable(gradient);