Issue
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??
Solution
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();
Answered By - Krishna Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.