android: Set link with <a href> in TextView - android

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"
}

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));
}

Html Styling in textview goes wrong Android

I am selecting a part of the TextView and on click of a "highlight" button, I am sending the start and the end index of selection to the database. Then I am loading all the start and end indexes from db and changing the color of text between them.
The problem is after once or twice, the app is changing the color of text that is not in selection.. and the selected part remains unchanged.
MY CODE:
When user selects and presses the highlight button
int i=contentText.getSelectionStart();
int j=contentText.getSelectionEnd();
db.insertHiglightIndex(String.valueOf(i),String.valueOf(j));
setHighlightedText();
The setHighlightedText() method..
String fullText=contentText.getText().toString();
for(int i=0; i<db.getAllStartIndex().size();i++){
String a=fullText.substring(Integer.parseInt(db.getAllStartIndex().get(i)),Integer.parseInt(db.getAllEndIndex().get(i)));
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
}
contentText.setText(Html.fromHtml(fullText), TextView.BufferType.SPANNABLE);
MY SCREENSHOTS.
The selection:
The Result:
Clearly the selected area is from "Garrick" to "Bart", and the result is from "entity" to "2012"
I am not able to understand why is this happening. I think there is some problem with this <font color='red'>"+a+"</font> line.
Thank you
It got wrong indexed because There is already added <font color='red'> in the beginning, So that in second time This tag is also counted as a part of string, So I suggest creating a new temporary String, assign same text to the String but after replacing the previous font tag it held. Use this syntax to remove previous font tag from originalString
String tempString = originalString.replaceAll("[<](/)?font[^>]*[>]", "");
After that work with only tempString. That means again add every previous font tag you have to tempString and set that text.
In next time again do the same first remove all font tag and again add all of them back in tempString as well as current selection using same loop you are using currently.
You have wrong indexes because you are modifying the fullText content within the loop.
Taking a look at this example you can figure it:
final TextView tv = (TextView) findViewById(R.id.textView);
tv.setText( "abcdefghijklmnopqrstuvwxyz0123456789");
String fullText= tv.getText().toString();
// your first iteration
String a = fullText.substring(1,3);
// a contains "ab"
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
After the first iteration full text contains now
a<font color='red'>bc</font>defghijklmnopqrstuvwxyz0123456789"
Then the substring() in the second iteration won't returns the substring base on your initial content.
If you want to be able to have multiple substrings colored in red you can try this:
String fullText = contentText.getText().toString();
StringBuilder result = new StringBuilder();
for(int i=0; i < db.getAllStartIndex().size(); i++){
fullText = applyFont(result, fullText, Integer.parseInt(db.getAllStartIndex().get(i)), Integer.parseInt(db.getAllEndIndex().get(i)));
}
// Add here the remaining content
result.append(fullText);
contentText.setText(Html.fromHtml(result.toString()), TextView.BufferType.SPANNABLE);
private String applyFont(StringBuilder result, String source, int from, int to){
result.append(source.substring(0, from));
result.append("<font color='red'>");
result.append(source.substring(from, to));
result.append("</font>");
return source.substring(to, source.length());
}

Android TextView change <a> background color

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

linkyfy some text in TextView

I have a String in TextView and I want to Linkify a substring from that string. for example:
click here to know more.
I'm getting the string dynamically. So i have to search if it has click here and convert that to link .How can I linkify "click here".
To find a pattern inside a text and replace it, use this:
Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
m.appendReplacement(sb, "click here");
result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();
yourTextView.setText(Html.fromHtml(strWithLink));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance())
This code will search inside your string and replaces all "click here" with a link.
And at the end, do NOT add android:autoLink="web" to you XML resource (section TextView), otherwise A-tags are not rendered correctly and are not clickable any longer.
did your tried like this
Click here
for setting it to textview
 
//get this thru supstring
String whatever="anything dynamically";       
String desc = "what you want to do is<a href='http://www.mysite.com/'>"+whatever+":</a>";
yourtext_view.setText(Html.fromHtml(desc));
String urlink = "http://www.google.com";
String link = "<a href=\"+urlink+ >link</a>";
textView.setText(Html.fromHtml(link));
Raghav has the right approach using the fromHtml() method, but if you're searching for for a String with a fixed length, you could do something like:
String toFind = "click here";
if(myString.indexOf(toFind) > -1){
String changed = myString.substring(0, myString.indexOf(toFind)) + "<a href='http://url.whatever'>" + myString.substring(myString.indexOf(toFind), myString.indexOf(toFind) + toFind.length()) + "</a>" + myString.substring(myString.indexOf(toFind) + toFind.length());
}
else {
//String doesn't contain it
}
When setting the actual text, you need to use: tv.setText(Html.fromHtml(yourText)); or else it will just appear as a String without any additives. The fromHtml() method allows you to use certain HTML tags inside your application. In this case, the tag which is used for linking.

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