I have the following:
textView.setText(Html.fromHtml("<font color=\"red\" size=\"24\">Hello</font>"));
The string 'Hello' does turn red but the size does not change.
It is as if the size attribute is just ignored, does anyone know why this is? Am I doing something wrong?
Size attribute seems not working.
You can use <small> or <big> (multiple times to increase the effect)
You can also use <h1> to <h6> (Header only, i.e. add a new line)
Its old-fashion, but it works well !
Yes, size attribute just ignored. Only "color" and "face" attributes are taken into account.
From Html class sources:
private void handleStartTag(String tag, Attributes attributes) {
if (tag.equalsIgnoreCase("br")) {
// We don't need to handle this. TagSoup will ensure that there's a </br> for each <br>
// so we can safely emite the linebreaks when we handle the close tag.
}
...
else if (tag.equalsIgnoreCase("font")) {
startFont(mSpannableStringBuilder, attributes);
}
...
}
private static void startFont(SpannableStringBuilder text,
Attributes attributes) {
String color = attributes.getValue("", "color");
String face = attributes.getValue("", "face");
int len = text.length();
text.setSpan(new Font(color, face), len, len, Spannable.SPAN_MARK_MARK);
}
Try this one,Its working for me,use small,big key words
TextView mBox = (TextView) findViewById(R.id.txt);
mBox.setText(Html.fromHtml("<font color=#cc0029>" + "<b>"
+ "Hiiiiiiiiii" + "</b>" + "<br />" + "<small>" + "description"
+ "</small>" + "<br />" + "<small>" + "DateAdded" + "</small>"));
Sergey Gotov is right. The only way to change text size it to use h1 - h6 tags.
EDIT: You can also implement TagHandler and use your own tags.
Look at Formatting and Styling on the android developpers site:
http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Or, on this old post of StackOverflow :
Highlighting Text Color using Html.fromHtml() in Android?
Related
I have a set of listpreferences which I am displaying in a PreferenceActivity screen. I would like to display a part of the text in the summary field with some formatting, say italics, or different colour.
What would be a good way to go about this?
I am using the following code to set the summary of a listpreference:
lp.setSummary(myText);
//E.g myText = "My name is SoAndSo";
//Required output : "My name is *SoAndSo* (in italics)
// or
// "My name is *SoAndSo* **(in green)**
You can format the text output in html, using html tags.
Here's one way:
mBox = new TextView(context);
mBox.setText(Html.fromHtml("My name is <i>SoAndSo</i>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));
For an unofficial list of tags supported by this method, refer to this link
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));
I have this code for setting the text of a TextView:
TextView txt = new TextView(this);
txt.setText(Html.fromHtml("<b>" + m.getTitle() + "</b>" + "<br />" + "<small>" + m.getText() + "</small>" + "<br />");
The <small> mark is working, but I'd like to set the text size according to my dimensions defined in the dimens.xml file, which I use for all other text in my application. Adding the TextView through an xml layout is not an option since I don't know how many TextViews I'll be adding.
Dimensions in the dimens.xml file are set up like <dimen name="text_size_320dp_small">16sp</dimen>.
How can I apply these dimensions to my text formatted with Html.fromHtml?
Thanks a lot.
I have tested following code myself. You can do it like this.
txt.setText(Html.fromHtml("<b>" + m.getTitle() + "</b>" + "<br />"
+ "<font textsize="
+ getResources().getDimension(R.dimen.text_size_320dp_small) + ">" + m.getText()
+ "</font>" + "<br />"));
[Updated]:
Just came up with some references and updates :
You can store this in strings.xml
<string name="mystring"><font size = "%s"></string>
In code you can write as:
int sptopx = getResources().getDimensionPixelSize(R.dimen.text_size_320dp_small);
Spanned modified = Html.fromHtml( context.getString(R.string.mystring, sptopx) );
myTextView.setText(spanned);
TextView txt = new TextView(this);
txt.setText(
Html.fromHtml(
"<b>" + m.getTitle() + "</b>" +
"<br />" +
modified +
">" + m.getText() + "</font>" +
"<br />"
)
);
for details about html tags support in TextViews you can check this link.
You can't directly, the small tag creates a RelativeSizeSpan with a proportion of .8f, which is hardcoded into the implementation of Html.fromHtml.
Leaves two options that I can see, set the text size to 20sp (which would make small work out to 16sp). Probably not ideal.
The other option is to use a custom tag <mySmall> by replacing all occurrences of <small> and </small> with <mySmall>& </mySmall>. And then call fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) with a TagHandler that integrates a AbsoluteSizeSpan into the output Editable.
Why don't you use txt.setSizeText(yoursize)? However you can retrieve your dimensions using this:
float yourDimen = getResources().getDimension(R.dimen.your_dimen_name);
So is it possible to change text size of part of the text in textview dynamically
Let's say we have a method that does that...what am I missing...I want to make x variable twice as big as y...they are string btw...
private void Data_transfer() {
test3.setText( x + " " + y);
}
You can use the Spannable type with a TextView to set multiple styles in one field.
In your case, you can do this like so, using the fromHtml() method which generates a Spannable string:
test3.setText( Html.fromHtml( "<font size='10'>" + x + "</font> <font size='5'>" + y + "</font>" ) );
And you can, of course, change 10 and 5 to whatever values you like.
private void Data_transfer() {
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome to 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