Android TextView change <a> background color - android

I want to change background color of a link in textview which was created using following code:
String htmlStr = "Click here: SO";
Spanned htmlSpanned = Html.fromHtml(htmlStr, this, null);
txtView.setText( htmlSpanned );
I used font tag but it didn't work.

Try using some css codes
The font tag can't change the background color of html links,
Try this code:
String htmlStr = "Click here: <a style='background-color:#00ff00' href=\'http://stackoverflow.com\'>SO</a>";
Spanned htmlSpanned = Html.fromHtml(htmlStr, this, null);
txtView.setText( htmlSpanned );

String htmlStr = "Click here: ";
String link = "<font color='blue'><a href=\'http://stackoverflow.com\'>SO</a></font>";
Spanned htmlSpanned = Html.fromHtml(htmlStr + link, this, null);
txtView.setText( htmlSpanned );
You can use the font tag to add color. Also can do something like:
int сolor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2);
Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString),
This grabs a color resource and strips it of the alpha channel value. Useful if you want to use a particular color else where in your project

Related

Change text color of bold html text

I want to change text color before displaying it to TextView.
For example,I am getting a text from server like
<b>Pratik<b/> has shared photo with <b>you</b>.
Now the requirements are to display Pratik and you with Bold style and Blue text color. I tried several ways using <span> tag, but I am not getting clear way to display it.
String htmlBody = "<b>Pratik<b/> has shared photo with <b>you</b>.";
String formattedBody = "<span>" + htmlBody + "</span><style>b { color: #309ce8 ; } span {font-family: 'Avenir', 'Heavy'; font-size: 17; }</style>";
SpannableString text = new SpannableString(formattedBody);
tvMessage.setText(text, TextView.BufferType.SPANNABLE); // This is not working as expected.
tvMessage.setText(Html.fromHtml(htmlBody)); // This is not working as expected.
Help me achieve that.
String htmlBody = "<b style='color:blue !important;'>Pratik</b> has shared photo with <b style='color:blue !important;'>you</b>.";
Your Solution is:
String styledText = "<b><font color='red'>Pratik</font><b/> has shared photo with <b><font color='red'>you</font></b>";
You have to use like this
public void methodName() {
String html = "Some text <b>here</b>, and some <b>there</b>";
String result = html.replace("<b>","<font color=\"#ff0000\"><b>").replace("</b>", "</b></font>");
textView.setText(Html.fromHtml(result));
}

in StringBuffer i want to add half bold text and half normal in append

how can i set half bold text by html.fromhtml i try but didn't work in append of BufferString out append its work fine please help me here is code
String amt = "AMOUNT: ";
Spanned tyyy =Html.fromHtml("<b>"+"TYPE: "+"</b>");
String Dat = "DATE: ";
String des = "DESCRIPTION: ";
buffer.append(Html.fromHtml("<b>"+amt+"</b>"+"<small>"+cc.getString(cc.getColumnIndex("AMOUNT"))+"</small>")+"\n");
buffer.append(tyyy+cc.getString(cc.getColumnIndex("TYPE"))+"\n");
If it doesn't need to be from HTML, you can use SpannableStringBuilder:
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("TYPE:");
// bold the current text
int boldStartIndex = 0;
int boldEndIndex = bulder.length();
builder.setSpan(new StyleSpan(Typeace.BOLD, boldStartIndex, boldEndIndex, Spanned.FLAG_EXCLUSIVE_EXCLUSIVE));
// append the rest, it will not be bolded
builder.append("the-rest-of-your-data");
You can then set the builder directly to a TextView via TextView.setText(builder);. This may be a better approach than using HTML, as HTML tags support isn't very well documented and may not be supported across various devices.

How to set Webview link color from resource

I have some HTML that I'm loading into a WebView and I need to customize the css styles. When it came to setting the link color directly from my Color resource I had some trouble. In the following example using linkColorManual worked but if I switched it to linkColor the css style was ignored:
String mime = "text/html";
String encoding = "utf-8";
String linkColor = getResources().getString(R.color.Link_Colour);
String linkColorManual = "#867970";
String html = "<!DOCTYPE HTML>\n<html>\n<head>\n<style>\n"
+ "body, html { font-family: 'sans-serif'; font-size:14px; color:#8B8D90;}\n"
+ "a {color:"+linkColorManual+";}\n"
+ "</style>\n</head>\n<body>" + post.getPostData().toString() + "</body>\n</html>";
WebView myWebView = (WebView) findViewById(R.id.post_content);
myWebView.loadDataWithBaseURL(post.getPostURL().toString(), html, mime, encoding, null);
This is the relevant line from my color.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<color name="Link_Colour">#867970</color>
...
</resources>
I'd rather not copy paste this hex color throughout my app. Why does it fail to apply the css if I load the color string directly from the resource?
Found the solution:
When retrieving an Android Color resource via getResources().getString(), I received an 8 character hex color NOT a 6 digit one that CSS can parse. From the example above this meant:
linkColor = #ff867970;
linkColorManual = #867970;
The extra two characters (#ff) at the front represent the Alpha (see Android Color docs for more info). To retrieve the 6 character CSS parsable color instead, I used the following:
int linkColorInt = getResources().getColor(R.color.Link_Colour);
String linkColor = "#" + Integer.toHexString(linkColorInt & 0x00FFFFFF);
You should just put your color in strings.xml like this:
<string name="Link_Colour">#223344</string>
Or if you want to stick with color, do this
int color = getResource().getColor(R.color.xyz);
String linkColor = "#" + Integer.toHexString(color)

android: Set link with <a href> in TextView

I create a TextView dynamically and want to set the text as linkable. Text value is "Google". I referred to internet & blogs like this, which shows the same way, but I couldn't produce the expected results.
I tried different ways, but the output I see is the whole text with text only. The code I have tried with is :
TextView tv1 = new TextView(this);
tv1.setLayoutParams(textOutLayoutParams);
// Make Linkable
tv1.setMovementMethod(LinkMovementMethod.getInstance());
tv1.setText(Html.fromHtml(l.getLeftString()));
/*SpannableString s = new SpannableString(l.getLeftString());
Linkify.addLinks(s, Linkify.WEB_URLS);
tv1.setText(s);
tv1.setMovementMethod(LinkMovementMethod.getInstance());
*/
dialogLayout.addView(tv1);
In my output I see "Google" and no link. I also tried Clean project & building it again, but no success.
I am looking to see only "Google" as underlined with blue color (as default) and on clicking Google, the browser open with http://google.com.
What is lacking in my code to get the output ?
BTW For REF : I use 64bit Win 7, Java, Eclipse, Android API 8-2.2
Any help is highly appreciated.
I finally got it working using the following code :
TextView tv1 = new TextView(this);
tv1.setLayoutParams(textOutLayoutParams);
tv1.setText(Html.fromHtml("" + l.getLeftString() + ""));
tv1.setClickable(true);
tv1.setMovementMethod (LinkMovementMethod.getInstance());
dialogLayout.addView(tv1);
l.getRightString() - contains a url like http:\www.google.com
l.getLeftString() - contains text for the url like "Go to Google"
RESULTS :
Text "Go to Google" on my dialog with blue color and underlined, and on clicking it the browser opens up and shwows the respective page. On returning/Exiting the browser it again comes to the app from the state where it had left.
Hope this helps.
Save your html in a string
<string name="link"><a href="http://www.google.com">Google</a></string>
Set textview ID to to
textViewLinkable
In main activity use following code:
((TextView) findViewById(R.id.textViewLinkable)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.textViewLinkable)).setText(Html.fromHtml(getResources().getString(R.string.link)));
I was also facing the same issue I resolved using following
String str_text = "<a href=http://www.google.com >Google</a>";
TextView link;
link = (TextView) findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
link.setText(Html.fromHtml(str_text));
for changing the link color to blue use
link.setLinkTextColor(Color.BLUE);
Here is my simple implementation tested up to Android N.
String termsText = "By registering, you are agree to our";
String termsLink = " <a href=https://www.yourdomain.com/terms-conditions.html >Terms of Service</a>";
String privacyLink = " and our <a href=https://www.yourdomain.com/privacy-policy.html >Privacy Policy</a>";
String allText = termsText + termsLink + privacyLink;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
((TextView) findViewById(R.id.text_terms_conditions)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.text_terms_conditions)).setText(Html.fromHtml(allText, Html.FROM_HTML_MODE_LEGACY));
}
else {
((TextView) findViewById(R.id.text_terms_conditions)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.text_terms_conditions)).setText(Html.fromHtml(allText));
}
txtview.setMovementMethod(LinkMovementMethod.getInstance());
Pass this statement to your textview, and in string.xml set an string as
<string name="txtCredits"> </string>
Now pass this string name " android:text="#string/txtCredits" to your xml class where the txtview is there .
use this code autolink-java On GitHub
like this
private String getLink(String string){
LinkExtractor linkExtractor = LinkExtractor.builder()
.linkTypes(EnumSet.of(LinkType.URL)) // limit to URLs
.build();
Iterable<Span> spans = linkExtractor.extractSpans(string);
StringBuilder sb = new StringBuilder();
for (Span span : spans) {
String text = string.substring(span.getBeginIndex(), span.getEndIndex());
if (span instanceof LinkSpan) {
// span is a URL
sb.append("<a href=\"");
sb.append(text);
sb.append("\">");
sb.append(text);
sb.append("</a>");
} else {
// span is plain text before/after link
sb.append(text);
}
}
return sb.toString(); // "wow http://test.com such linked"
}

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