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.
Related
I'm trying to remove all text tagged like this (including the tags)
<tag>TEXT</tag>
from a String.
I have tried
.replaceAll("<tag>.+/(tag)*>", "")
or
.replaceAll("<tag>.*(tag)*>", "")
but neither works correctly and I can't replace the tagged text with ""
I don't know exactly what you want, so here are a few options:
String text = "ab<tag>xyz</tag>cd";
// Between
text.replaceAll("<tag>.+?<\/tag>", "<tag></tag>"); // ab<tag></tag>cd
// Everything
text.replaceAll("<tag>.+?<\/tag>", ""); // abcd
// Only tags
text.replaceAll("<\/?tag>", ""); // abxyzcd
EDIT:
The problem was the missing ? after the .+. The question mark only matches the first occurence, so it works when multiple tags are present which was the case.
Change to this ,
String nn1="<tag>TEXT</tag>";
nn1=nn1.replace("<tag>","");
nn1=nn1.replace("</tag>","");
OR
String nn1="<tag>TEXT</tag>";
nn1=nn1.replaceAll("<tag>","");
nn1=nn1.replaceAll("</tag>","");
Output : TEXT
I hope this helps you.
public static void removeTAG()
{
String str = "<tag>Your Long String</tag>";
for(int i=0;i<str.length();i++)
{
str = str.replace("<tag>", "");
str = str.replace("</tag>", "");
}
System.out.println(str);
}
Here what i did and output was as expected
Output Your Long String
You can use the below regular expression.
.replaceAll("<tag>.+?<\/tag>", "<tag></tag>");
This removes all the tags whether it's an HTML or an XML tag.
I was wondering if there is a way to get the html markup.
For example:
finalString = " <font color='#2caeac'>#test</font>";
editetext.setText(Html.fromHtml(finalString));
Now if I want to edit my edittext like this:
new_string = edittext.getText().toString(); // getting my "#test"`
new_string = new_string+"<font color='red'>newString</font>";
edittext.settext(Html.fromHtml(new_string));
Then my new_string doesn't catch the color of "finalString".
How is it possible to get the color of finalString?
I thought to a little tricky solution that involves the replace of tags in an HTML text.
The explanation is in code's comments.
String finalString = "<font color='#2caeac'>#test</font>";
textView.setText(Html.fromHtml(finalString));
// get the text with html
String new_string = Html.toHtml(textView.getText());
// the result will be something like <p dir="something">text_with_html_here</p>
// get the layout direction (above api 17 you can't use getDirection())
final int direction = Character.getDirectionality(Locale.getDefault().getDisplayName().charAt(0));
// check if it's RTL
boolean isRTL = direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT || direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
String layoutDirection = isRTL ? "rtl" : "ltr";
// replace raw tags added with toHtml()
new_string = new_string.replace("<p dir=\"" + layoutDirection + "\">", "").replace("</p>", "");
// use the String
new_string = new_string + "<font color='red'>newString</font>";
textView.setText(Html.fromHtml(new_string));
1.I am getting data from server storing inside string Array.
2.then i want to show in Android TextView ,each TextView line should Contain 2 strings(Like Skill Sets) from String array.
3.then need to add cross Image in right side of the Textview.
please help me, how to achieve this.
String mystring = "This is my first sentence";
String arr[] = mystring.split(" ", 3);
String firstWord = arr[0]; //This
String secondWord = arr[1]; //is
String theRest = arr[2]; //my first sentence
yourtextview.setText(firstWord +" "+ secondWord);
and regarding for Image in right side of the Textview put this in ur txtview'sxml.
android:drawableRight="#drawable/image"
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"
}
In my android app, I am getting the String from an Edit Text and using it as a parameter to call a web service and fetch JSON data.
Now, the method I use for getting the String value from Edit Text is like this :
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
Now normally it works fine, but if we the text in Edit Text contains space then my app crashes.
for eg. - if someone types "food" in the Edit Text Box, then it's OK
but if somebody types "Indian food" it crashes.
How to remove spaces and get just the String ?
Isn't that just Java?
String k = edittext.getText().toString().replace(" ", "");
try this...
final EditText edittext = (EditText) findViewById(R.id.search);
String k = edittext.getText().toString();
String newData = k.replaceAll(" ", "%20");
and use "newData"
String email=recEmail.getText().toString().trim();
String password=recPassword.getText().toString().trim();
In the future, I highly recommend checking the Java String methods in the API. It's a lifeline to getting the most out of your Java environment.
You can easily remove all white spaces using something like this. But you'll face another serious problem if you just do that. For example if you have input
String input1 = "aa bb cc"; // output aabbcc
String input2 = "a abbcc"; // output aabbcc
String input3 = "aabb cc"; // output aabbcc
One solution will be to fix your application to accept white spaces in input string or use some other literal to replace the white spaces. If you are using only alphanumeric values you do something like this
String input1 = "aa bb cc"; // aa_bb_cc
String input2 = "a abbcc"; //a_abbcc
String input3 = "aabb cc"; //aabb_cc
And after all if you are don' caring about the loose of information you can use any approach you want.