Android get color as string value - android

If i defined a color in resources
<resources>
<color name="someColor">#123456</color>
</resources>
it's possible to set color by its id, like
view.setTextColor(R.color.someColor);
Is it also possible to get color string value from colors.xml?
Something like
colorStr = getColor(R.color.someColor);
// -> colorStr = "#123456"
If yes, can anybody give an example?
Thank you

This is your answer
colorStr=getResources().getString(R.color.someColor);
you will get
colorStr = "#123456"

Just for the sake of easy copypasta:
"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color));
Or if you want it without the transparency:
"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color) & 0x00ffffff);

All of the solutions here using Integer.toHexString() break if you would have leading zeroes in your hex string. Colors like #0affff would result in #affff. Use this instead:
String.format("#%06x", ContextCompat.getColor(this, R.color.your_color) & 0xffffff)
or with alpha:
String.format("#%08x", ContextCompat.getColor(this, R.color.your_color) & 0xffffffff)

The answers provided above are not updated.
Please try this one
String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff);

Cause getResources().getColor need api > 23. So this is better:
Just for the sake of easy copy & paste:
Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) );
Or if you want it without the transparency:`
Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) & 0x00ffffff );

For API above 21 you can use
getString(R.color.color_name);
This will return the color in a string format.
To convert that to a color in integer format (sometimes only integers are accepted) then:
Color.parseColor(getString(R.color.color_name));
The above expression returns the integer equivalent of the color defined in color.xml file

It works for me!
String.format("#%06x", ContextCompat.getColor(this, R.color.my_color) & 0xffffff)

Add #SuppressLint("ResourceType") if an error occurs. Like bellow.
private String formatUsernameAction(UserInfo userInfo, String action) {
String username = userInfo.getUsername();
#SuppressLint("ResourceType") String usernameColor = getContext().getResources().getString(R.color.background_button);
return "<font color=\""+usernameColor+"\">" + username
+ "</font> <font color=\"#787f83\">" + action.toLowerCase() + "</font>";
}

I don't think there is standard functionality for that. You can however turn the return in value from getColor() to hex and turn the hex value to string.
hex 123456 = int 1193046;

This is how I've done it:
String color = "#" + Integer.toHexString(ContextCompat.getColor
(getApplicationContext(), R.color.yourColor) & 0x00ffffff);

Related

Is there any way to create a textview with different color or with different styles in kotlin

I was learning DataStore in android development and in my project user will write a name in first activity.
and when user clicks button goes to second activity and my problem starts here:
but i want to show it like these photos:
or like this photo
I mean i want to make name colorful,but not in order,randomly
what i have tried:
i tried to take my name string to foreach but i could not change char colors my opinion was in foreach loop give any random color to every char but i could not.
then i tried SpannableStringBuilder and i get the result and these are my codes:
var random = Random()
var number1 = random.nextInt(value?.length?.minus(1) !! )
var number2 = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
random.ints(number1,value?.length !!).findFirst().asInt
} else {
TODO("VERSION.SDK_INT < N")
}
val spannableString = SpannableStringBuilder(value)
spannableString.setSpan(ForegroundColorSpan(Color.RED),
number1,number2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
textViewName.text = spannableString
i use just red color now but if i can make it randomly,i can make with other colors.
i hope you understand my problem and thanks for helping.
Since you have already figured out how to apply span to a specific character, for random colors you can simply make a list of colors as follows
val colorList = arrayListOf(Color.RED, Color.BLUE, Color.GREEN, Color.BLACK)
and so on and while you are assigning the span you can simply go like this
val randomColor = colorList.random()
colorList.remove(randomColor)
spannableString.setSpan(ForegroundColorSpan(randomColor),
number1,number2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

How to change text color of the part of the TextView?

I have simple textView controler on my application.
On this textView i set the text "123456789" - the text color is black.
I want that the three last digit ( 789 ) will be shown with red text color.
Is there any simple way to do it without using two textView controls
(one will contain "123456" in black and second will contain "789" in red )
Try This:
Set TextView as a HTML using SpannableTextView
String text = "<font color='black'>123456</font><font color='red'>789</font>";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
You can use this method
public static final Spannable getColoredString(Context context, CharSequence text, int color) {
Spannable spannable = new SpannableString(text);
spannable.setSpan(new ForegroundColorSpan(color), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
then later you call is by using
textview.append(getColoredString(this, "Hi!", ContextCompact.getColor(this, R.color.red)));
textview.append(getColoredString(this, "User", ContextCompact.getColor(this, R.color.green)));
You can use
myTextView.setText(Html.fromHtml(stringB + "<font color=red>" + stringA + "</font>);
You can use SpannableString is an excellent way to style strings in a TextView.
Demo
SO Post
You can either use HTML banners in your java class:
Example:
textElement.setText(Html.fromHtml("123456 <fontcolor='#FF0000'>789</font>"));
Or use CData format in your XML file:
Example:
<string name="numbers"><![CDATA[123456<fontcolor="#FF0000">789</font>]]></string>
I hope that helped you ;)
You can use this.
textview.setText(Html.fromHtml(getString(R.string.stringname) + "" + " *" + "", Html.FROM_HTML_MODE_LEGACY));

set textview's text using Html.fromHtml inside a loop?

Is possible to use Html.fromHtml to the String fetchData, to change some of the text style? This text assigned to a textView outside the loop.
Here is the related code:
if( c != null && c.moveToFirst() ){
while (c.isAfterLast()==false) {
String gtWord = c.getString(1);
String gtDef = c.getString(2);
fetchData = fetchData + getResources().getString(R.string.wordLabel) + gtWord + "\n"
+ getResources().getString(R.string.transLabel) + gtDef + "\n\n";
c.moveToNext();
}
getData.setText(fetchData)
Right now I'm using strings.xml in which I've set the text like this:
<b>Word: </b>
but the style is ignored. I'found some related questions and I've tried to do it without using strings.xml also, but the only tag recognized is the , all others ignored. I'm supposing that the problem is that I'm using mixed variables and hardcoded text inside loop, because I tested it outside the loop like this:
getData.setText(Html.fromHtml("<b>This<b/> is <u>underlined<u/> text")
and it's working.
Declaire your string like this
<string name="wordLabel"><![CDATA[<b>Word: </b>]]></string>
From documentaion you can also write it as
<string name="word_label"><b>Word: </b></string> // here I have chnaged your string name wordLabel to word_label. you should follow naming convension.
Notice that the opening bracket is HTML-escaped, using the < notation.

Android convert color int to hexa String

public static int RGB(float[] hsv) {
return Color.HSVToColor(hsv);
}
this function add an int, froma color. how can i convert that int to a hexa string: #efefef
The answer of st0le is not correct with respect to colors. It does not work if first color components are 0. So toHexString is useless.
However this code will work as expected:
String strColor = String.format("#%06X", 0xFFFFFF & intColor);
Here are 2 ways to convert Integer to Hex Strings...
int n = 123456;
System.out.println(String.format("#%X", n)); //use lower case x for lowercase hex
System.out.println("#"+Integer.toHexString(n));
If you want to convert to javascript format:
val hexColor = String.format("%06X", 0xFFFFFFFF.and(R.color.text.toColorInt(context).toLong()))
val javascriptHexColor = "#" + hexColor.substring(2) + hexColor.substring(0, 2)
Use this way
Java:
String hexColor = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))
Kotlin:
var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"

Highlighting Text Color using Html.fromHtml() in Android?

I am developing an application in which there will be a search screen
where user can search for specific keywords and that keyword should be
highlighted. I have found Html.fromHtml method.
But I will like to know whether its the proper way of doing it or
not.
Please let me know your views on this.
Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Using color value from xml resource:
int labelColor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!
Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE);
This can be achieved using a Spannable String. You will need to import the following
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
And then you can change the background of the text using something like the following:
TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Your text here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!
Alternative solution: Using a WebView instead. Html is easy to work with.
WebView webview = new WebView(this);
String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";
webview.loadData(summary, "text/html", "utf-8");
String name = modelOrderList.get(position).getName(); //get name from List
String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
/* check API version, according to version call method of Html class */
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText(context.getString(R.string._5687982) + " ");
holder.textViewName.append(Html.fromHtml(text));
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("123456" + " "); //set text
holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)); //append text into textView
}
font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")
To make part of your text underlined and colored
in your strings.xml
<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u></string>
then in the activity
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
and for clickable links:
<string name="text_with_link"><![CDATA[<p>text before linktitle of link.<p>]]></string>
and in your activity:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
First Convert your string into HTML then convert it into spannable. do as suggest the following codes.
Spannable spannable = new SpannableString(Html.fromHtml(labelText));
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));
It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.
Adding also Kotlin version with:
getting text from resources (strings.xml)
getting color from resources (colors.xml)
"fetching HEX" moved as extension
fun getMulticolorSpanned(): Spanned {
// Get text from resources
val text: String = getString(R.string.your_text_from_resources)
// Get color from resources and parse it to HEX (RGB) value
val warningHexColor = getHexFromColors(R.color.your_error_color)
// Use above string & color in HTML
val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"
// Parse HTML (base on API version)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
}
And Kotlin extension (with removing alpha):
fun Context.getHexFromColors(
colorRes: Int
): String {
val labelColor: Int = ContextCompat.getColor(this, colorRes)
return String.format("%X", labelColor).substring(2)
}
Demo

Categories

Resources