This question already has answers here:
How to make normal links in TextView clickable?
(5 answers)
Closed 6 years ago.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="legalText">
By using this xxxxxxxxxxx app, I agree to the Terms of Use and Notice of Privacy Policy [[need official name]] in this app. I understand that use of this xxxxxxxxx app is at my own risk and discretion. I understand and agree that the health information I give to xxxxxxx in this app is truthful and will be the only source of health information used by the xxxxxxxxxx providers during the course of my evaluation and treatment through xxxxxxxxxx. Also, as part of my use of the xxxxxxxx app, I agree that I will not use this app for any purpose that is prohibited by the xxxxxxxx Terms of Use [[link to Terms]] and Consent to Telehealth [[Link to Consent to Telehealth]]”, and Consent to Request Medical Services [insert link to Consent to Request Medical Services].
</string>
</resources>
I need to put links to other xml pages and html pages at bracket locations in this xml file. How do I do that?
Here's what you can do:
Break that one string into several string resources (atleast separate the app-name and links to a different string resource.
Contruct the full legalText by joining the substrings found in step 1. Use the <a href= "link"><a/> tag for the substrings with link. You can style the rest of the substrings accordingly, as you get the idea.
Use the Html.fromHtml method to show the formatting:
Spannable text = (Spannable)Html.fromHtml(legalText);
//this one here to get the links clickable:
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(text);
You might need to get rid of extra underlines at this point, therefore use this method:
private void stripUnderlines(TextView textView) {
Spannable s = (Spannable)textView.getText();
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span: spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
As far as i know, it is not possible to add links directly into strings, but you can create different strings and assemble your text with different TextViews and set OnClickListeners and a link-style to the TextViews you want to add link.
If you develop in java and Android Studio, you only have to set an onClickListener on the TextView the same way you do for a button.
You should also add styles such as underline or Color to let the user know there is a link.
Related
Let’s say you have the string:
"https://google.com to go to google. https://amazon.com to go to Amazon."
In a TextView, how would you replace the url’s with a link that shows “Click here” (or “Haz clic aquí” in spanish) and would take you to the correct url?
Keep in mind that the text is dynamic, it’s retrieved from the API, and there is no way to know if or how many links may be in any given post.
The finished product should look like this:
“Click here to go to google. Click here to go to Amazon.”
After many many hours…
Here is my solution.
I put this code inside the RecyclerView adapter's onBindViewHolder().
// replace url links with clickable link that says "Click here" (or "Haz clic aquí" in Spanish).
// link color is set in TextView in the xml.
// SpannableStringBuilder is mutable, so we can replace the link.
SpannableStringBuilder spannableStringBuilder = new
SpannableStringBuilder(newsFeedItem.getBody());
// use Linkify to automatically set all Url's in the string.
Linkify.addLinks(spannableStringBuilder,Linkify.WEB_URLS);
//do this process for each Url
for (URLSpan urlSpan: spannableStringBuilder.getSpans(0,spannableStringBuilder.length(),URLSpan.class)){
int start = spannableStringBuilder.getSpanStart(urlSpan);
int end = spannableStringBuilder.getSpanEnd(urlSpan);
// put whatever you want it to say into the next line where I wrote "Click here".
SpannableString customLinkSpannableString = new SpannableString("Click here");
customLinkSpannableString.setSpan(urlSpan,0, customLinkSpannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.replace(start, end, customLinkSpannableString);
}
// now set the fixed up string into the TextView and set LinkMovementMethod.
textView.setText(spannableStringBuilder);
textView.setMovementMethod(LinkMovementMethod.getInstance());
I have a textview which can contain links like https://www.google.com and hyper links with anchor tag Google
Now, I have added the below properties on this textview.
Linkify.addLinks(textview, Linkify.WEB_URLS);
textview.setMovementMethod(LinkMovementMethod.getInstance());
But the links like https://www.google.com these are coming fine in blue and redirecting to the page but anchor tags are not coming in blue and they are not redirecting it.
So, I want to make my textview to render both type of links: direct links and hyper links. How can I do this.
Linkify (the way you've invoked it) only knows to convert things that actually look like web URLs (i.e. they begin with http or https, followed by colon and two slashes, etc. etc).
If you want to convert something else into links, you will have to add some more parameters to Linkify to give it more smarts to convert what you want. You can create a MatchFilter and a TransformFilter then call Linkify.addLinks(TextView text, Pattern p, String scheme, Linkify.MatchFilter matchFilter, Linkify.TransformFilter transformFilter)
But it looks to me like you want to take a word like "Google" and add a link for "https://www.google.com". That's not something that can be scanned. For that, you need to use a SpannableStringBuilder. Your code might look something like this:
String text = "This is a line with Google in it.";
Spannable spannable = new SpannableString(text);
int start = text.indexOf("Google");
int end = start + "Google".length();
URLSpan urlSpan = new URLSpan("https://www.google.com");
spannable.setSpan(urlSpan, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(spannable);
It's mentioned in javadoc of Linkify#addLinks(Spannable, Int) that:
...If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text.
Although it is not mentioned in Linkify#addLinks(TextView, Int) which you're using, it appears that they follow the same behavior and existing links (i.e. the 'anchor tags' in your question) would be removed before linkify.
To workaround and preserve existing links ('anchor tags' in your case), you need to backup existing spans (i.e. TextView#getText --> convert to Spanned --> use Spanned#getSpans to list existing links --> use Spanned#getSpanStart and Spanned#getSpanEnd and Spanned#getSpanFlags to retrieve the settings of each)
After linkify, re-add the spans (i.e. TextView#getText --> convert to Spannable --> use Spannable#setSpan to re-add the links --> Set the Spannable back with TextView#setText)
Depending on your case, you might also need to check for overlapping 'anchor tags' and 'linkify links' and adjust accordingly...
As you see, this is quite tedious and complex and error prone to code. To simplify things, I have just incorporate all these into Textoo library for reuse and sharing. With Textoo, you can achieve the same by:
TextView myTextView = Textoo
.config((TextView) findViewById(R.id.view_location_disabled))
.linkifyWebUrls()
.apply();
Textoo will preserve exiting links and linkify all non-overlapping web urls.
//the string to add links to
val htmlString = "This has anchors and urls http://google.com also Google."
//Initial span from HtmlCompat will link anchor tags
val htmlSpan = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_LEGACY) as Spannable
//save anchor links for later
val anchorTagSpans = htmlSpan.getSpans(0, htmlSpan.length, URLSpan::class.java)
//add first span to TextView
textView.text = htmlSpan
//Linkify will now make urls clickable but overwrite our anchor links
Linkify.addLinks(textView, Linkify.ALL)
textView.movementMethod = LinkMovementMethod.getInstance()
textView.linksClickable = true
//we will add back the anchor links here
val restoreAnchorsSpan = SpannableString(textView.text)
for (span in anchorTagSpans) {
restoreAnchorsSpan.setSpan(span, htmlSpan.getSpanStart(span), htmlSpan.getSpanEnd(span), Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
//all done, set it to the textView
textView.text = restoreAnchorsSpan
I want to show registered or trademark symbol in android string.I tried using Unicode characters like
® and #reg; also.But it's not working.Can somebody please tell me how to display these symbols.Thanks in advance
Add this line in your TextView code
android:text="\u00AE"
Also try this Ⓡ symbol use ® and trademark ™ symbol ™
Add this line in your strings.xml
<string name="registered_symbol">®</string>
Variant 1 -- just paste the appropriate character
make sure you have the strings.xml in correct encoding: <?xml version="1.0" encoding="utf-8"?>
get the character from e.g. here:
REGISTERED SIGN: http://www.fileformat.info/info/unicode/char/ae/index.htm
TRADE MARK SIGN: http://www.fileformat.info/info/unicode/char/2122/index.htm
Variant 2 -- use html entities
In the linked pages you can also find the corresponding HTML entities ® and ™.
you have to set the text as HTML in your code, like this:
yourTextView.setText(Html.fromHtml(getString(R.string.your_text_entry)));
I hope this helped.
Declare a String in string.xml file like below,
<string name="registered">®</string>
Now you can access it by calling this String variable.
If you want to do it by html then try this, way
String htmlRegistered = "<html><body>My Trade mark is ®</body></html>";
Update from your Comment:
private String[] m_listImmunisations = new String[]
{ "<html><body>Hepatitis B (H-B-Vax® II)</body></html>",
"<html><body>HPV (Cervarix®)</body></html>",
"<html><body>HPV (Gardasil®)</body></html>"
}
Use "\u00AE" to replace that symbol.
To make it on top right corner, you can use SuperscriptSpan like following, replace the startIndex and endIndex with the position of your trademark character. Be careful with the size of the text, you may need some density independent size here probably to make it work on all screens.
Spannable span = new SpannableString(title);
span.setSpan(new TextAppearanceSpan(null, 0, 60, null, null), (int)startIndex, (int)endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new SuperscriptSpan(), (int)startIndex, (int)endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(span);
I'm trying to add a link to a Twitter profile in an about box. 'Regular' links such as email address and web address are handled by
android:autoLink="email|web"
in about.xml, but for a Twitter profile page I need to use html code in my strings.xml. I've tried:
<string name="twitter">Follow us on <a href=\"http://www.twitter.com/mytwitterprofile">Twitter: #mytwitterprofile</a></string>
which renders html markup on the about box.
I've also tried:
<string name="twitter">Follow us on Twitter: #mytwitterprofile</string>
which display the text "Follow us on Twitter: #mytwitterprofile", but it is not a hyper-link.
How do I do this seemingly simple task!?
Cheers,
Barry
The problem is your "a href" link tags are within strings.xml and being parsed as tags when strings.xml is parsed, which you don't want. Meaning you need to have it ignore the tags using XML's CDATA:
<string name="sampleText">Sample text <![CDATA[link1]]></string>
And then you can continue with Html.fromHtml() and make it clickable with LinkMovementMethod:
TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
The simple answer is that the TextView does not support <a> tags. AFAIK, it only supports basic formatting such as <b>, <i> and <u>. However, if you supply android:autoLink="web", the following string:
<string name="twitter">Follow us at twitter.com/mytwitterprofile</string>
Will turn twitter.com/mytwitterprofile into a proper link (when set via XML like android:text="#string/twitter"; if you want to set it from code, you'll need the Html.fromHtml method someone else posted in an answer).
I'm not too sure how to link using 'strings', but you could set text of the EditText or TextView using fromHtml...
TextView text = (TextView) findViewById(R.id.text);
text.setText(Html.fromHtml("Google Link!"));
text.setMovementMethod(LinkMovementMethod.getInstance());
Ok right , i asked how to create a random number from 1-100 for android and i came to this
TextView tv = new TextView(this);
int random = (int)Math.ceil(Math.random()*101);
tv.setText("Your Number Is..."+ random );
What this does is create the default kinda "hello world" style text view and says "Your Number Is.... [Then Random Number]
My problem is that i cant change the layout of this text , because it is not defined in XML, if someone could tell me how to change the style , or like make the random number into a string so i could use it for any Textview layout that would be great ..
Thanks :)
If by change the style you mean the text color, text size, and you want to change them programmatically, have a look at the setTextColor and setTextSize methods.
More info here
If you want more advanced formatting to set programmatically, see this link.
The below example demonstrates how to make your text bold and italic.
tv.setText("Your Number Is..."+ random, TextView.BufferType.SPANNABLE );
Spannable myText = (Spannable) tv.getText();
myText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC),0,myText.length(),0);
Edit:
Try the below for the android:textSize="100dp" and android:gravity="center" :
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 100);
tv.setGravity(Gravity.CENTER);
Putting it into a string is easy.
String randomAsAString = Integer.toString(random)
You can then use the XML properties of the TextView to change its formatting, such as android:textSize="30dp" or android:textColor="#900".
By the way, if you're happy with the answer to your previous question, you should go back and mark an answer as "Accepted". That gives 'reputation' points to the person whose answer you accepted and closes the question so that people don't think you're still waiting for a better answer. You can read more about reputation in the FAQ.
Edit:
You can't reference the string entirely in xml while still giving it a random number. This is because the "#string/some_string" format only allows unchangeable strings. The execption to this is using parameters, e.g. setting the string as
<string name="random_number">The random number is %d</string>
Then you could call up that string using something like
yourTextView.setText(this.getString(R.string.random_number, random))
As for your other question about setting a background to a textView, that's also easy.
yourTextView.setBackgroundDrawable(R.drawable.....)
You should take advantage of Eclipse's autocomplete feature... it makes finding these commands a lot easier. For example, simply type the name of your TextView followed by a period, pause half a second for the list of options to come up, then "setB" and it should then filter the list to the three setBackground Drawable/Resource/Color options.
tv.setText(Html.fromHtml("Your number is: <b>" + random + "</b>"));
For basic HTML text-styling tags.
You could also do something like this.
Define your string in strings.xml like:
<string name="your_number_is">Your number is <xliff:g id="number">%s</xliff:g>.</string>
Create a TextView in a layout xml:
<TextView android:id="#+id/your_number_is"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/your_number_is"
android:gravity="center"
android:textSize="100dip"
/>
Then your code would look like:
TextView tv = (TextView) findViewById(R.id.your_number_is);
int random = (int)Math.ceil(Math.random()*101);
tv.setText(getString(R.string.your_number_is, random));
This will make it a lot easier when you later on would like to change your text or maybe localize your app.
if you have thead troubles use this:
new Thread(){
public void run(){
TextView v = (TextView)findViewById(R.id.mytext);
v.setText("TEST");
}
}.start();