clickable word inside TextView in android - android

I have TextView with text that changed dynamically. This text contain strings like <a href='myWord'>myWord</a>. I want that after click to this "link" myWord appear in the EditText in the same activity.
This is my code:
txt.setText(Html.fromHtml("...<a href='link'>link</a>..."));
txt.setMovementMethod(LinkMovementMethod.getInstance());
It's work well for URLs inside href attribute, but there is an error for another format.
I found a lot of similar questions on the StackOverflow but all of them were about url links. In my app I want create "link" inside activity.
In general, I can change tag to some another if it's depend...
Please help me!
Thank you!
-----SOLVED-----
Thank you Jacob Phillips for idea!
May it will be interesting someone in future.
This is a code:
//This is my string;
String str = "<b>Text</b> which contains one <a href='#'>link</a> and another <a href='#'>link</a>";
//TextView;
TextView txt = new TextView(this);
//Split string to parts:
String[] devFull = data[v.getId()][1].split("<a href='#'>");
//Adding first part:
txt.append(Html.fromHtml(devFull[0]));
//Creating array for parts with links (they amount always will devFull.length-1):
SpannableString[] link = new SpannableString[devFull.length-1];
//local vars:
ClickableSpan[] cs = new ClickableSpan[devFull.length-1];
String linkWord;
String[] devDevFull = new String[2];
for(int i=1; i<devFull.length; i++){
//obtaining 'clear' link
devDevFull = devFull[i].split("</a>");
link[i-1] = new SpannableString(devDevFull[0]);
linkWord = devDevFull[0];
cs[i-1] = new ClickableSpan(){
private String w = linkWord;
#Override
public void onClick(View widget) {
// here you can use w (linkWord)
}
};
link[i-1].setSpan(cs[i-1], 0, linkWord.length(), 0);
txt.append(link[i-1]);
try{
txt.append(Html.fromHtml(devDevFull[1]));
}
catch(Exception e){}
}

This should do the trick. Just change your edittext's text in the OnClickListener. It may be able to be reduced but this should work.
private void foo() {
SpannableString link = makeLinkSpan("click here", new View.OnClickListener() {
#Override
public void onClick(View v) {
// respond to click
}
});
// We need a TextView instance.
TextView tv = new TextView(context);
// Set the TextView's text
tv.setText("To perform action, ");
// Append the link we created above using a function defined below.
tv.append(link);
// Append a period (this will not be a link).
tv.append(".");
// This line makes the link clickable!
makeLinksFocusable(tv);
}
/*
* Methods used above.
*/
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
}
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
/*
* ClickableString class
*/
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
#Override
public void onClick(View v) {
mListener.onClick(v);
}
}

Better approach is
SpannableString ss = new SpannableString("Android is a Software stack");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
startActivity(new Intent(MyActivity.this, NextActivity.class));
}
};
ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//where 22 and 27 are the starting and ending index of the String. Now word stack is clickable
// onClicking stack it will open NextActiivty
TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());

You can use below code;
SpannableString myString = new SpannableString(Html.fromHtml("Please "+"<font color=\"#F15d36\"><u>"+"login"+"</u></font>" +" or "+ "<font color=\"#F15d36\"><u>"+"sign up"+ "</u></font>"+" to begin your YupIT experience"));
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Toast.makeText(getContext(),"dfsgvdfs",Toast.LENGTH_SHORT).show();
}
};
ClickableSpan clickableSpan1 = new ClickableSpan() {
#Override
public void onClick(View textView) {
Toast.makeText(getContext(),"dfsgvdfs",Toast.LENGTH_SHORT).show();
}
};
myString.setSpan(clickableSpan,6,12,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(clickableSpan1,15,23,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(new ForegroundColorSpan(Color.parseColor("#F15d36")),6, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(new ForegroundColorSpan(Color.parseColor("#F15d36")),15,23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvFound.setMovementMethod(LinkMovementMethod.getInstance());
tvFound.setText(myString);

The best workaround I know is to create your own Button class. You could make the Button have a transparent background so that only the text is seen by the user. Then when the Button is pressed down change the TextColor and TextStyle of the button to be a darker color and underlined. This will work exactly as a link does. You can then use startActivity to go to the appropriated activity. You should not use hyperlinks to connect to other activities within your application.

My personal opinion would be to make a second textview containing the text that you want to be your link. Then you could do your action in the onClick of this second textView . Also as zzzzzzzzzzz stated above, you could choose to change the font properties of that text to whatever you want once it has been clicked.

To make it full answer with mixing answers;
private void textAreaInit()
{
String str = "<a href='#'>Link 1</a> and <a href='#'>Link2</a> is here.";
TextView tv = mConfirmText;
String[] devFull = str.split("<a href='#'>");
tv.append(Html.fromHtml(devFull[0]));
SpannableString[] link = new SpannableString[devFull.length-1];
ClickableSpan[] cs = new ClickableSpan[devFull.length-1];
String linkWord;
String[] devDevFull = new String[2];
for(int i=1; i<devFull.length; i++)
{
//obtaining 'clear' link
devDevFull = devFull[i].split("</a>");
link[i-1] = new SpannableString(devDevFull[0]);
linkWord = devDevFull[0];
final String a = linkWord;
cs[i-1] = new ClickableSpan()
{
private String w = a;
#Override
public void onClick(View widget) {
if(w.equals("Link 1"))
{
Intent intent = new Intent(PrintPropertiesActivity.this, ViewerAcivity.class);
intent.putExtra("title", "Link1");
intent.putExtra("uri", "link1");
intent.putExtra("type", "1");
startActivity(intent);
}
else
{
Intent intent = new Intent(PrintPropertiesActivity.this, ViewerAcivity.class);
intent.putExtra("title", "Link2");
intent.putExtra("uri", "link2");
intent.putExtra("type", "2");
startActivity(intent);
}
}
};
link[i-1].setSpan(cs[i-1], 0, linkWord.length(), 0);
tv.append(link[i-1]);
try{
tv.append(Html.fromHtml(devDevFull[1]));
}
catch(Exception e){}
}
makeLinksFocusable(tv);
}
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}

Related

Capture http link click event in android textview

I have a link in android textview. I am not able to capture the link click event.
String text = "http:://www.google.com is a google link";
textview.setText(text);
"http:://www.google.com" this span of string is clickable in textview. I want to capture that particular click event.
I tried the following.
public static void setTextView(TextView text, CharSequence sequence) {
UoloLogger.i(TAG, "Setting string :: "+sequence);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for(URLSpan span : urls) {
makeLinkClickable(strBuilder, span);
}
text.setText(strBuilder);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
public static void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
public void onClick(View view) {
UoloLogger.i(TAG, span.getURL());
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
I started setting text into my textview using setTextView() method. I am getting URLSpan array is empty even if i am having the links.
String text = "http:://www.google.com is a google link";
setTextView(textView, text);
Sorry for the bad english. I think, i have explained my problem. Can someone help me.
public static void setLinkclickEvent(TextView tv, HandleLinkClickInsideTextView clickInterface) {
String text = tv.getText().toString();
String str = "([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])";
Pattern pattern = Pattern.compile(str);
Matcher matcher = pattern.matcher(tv.getText());
while (matcher.find()) {
int x = matcher.start();
int y = matcher.end();
final android.text.SpannableString f = new android.text.SpannableString(
tv.getText());
InternalURLSpan span = new InternalURLSpan();
span.setText(text.substring(x, y));
span.setClickInterface(clickInterface);
f.setSpan(span, x, y,
android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(f);
}
tv.setLinksClickable(true);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setFocusable(false);
}
public static class InternalURLSpan extends android.text.style.ClickableSpan {
private String text;
private HandleLinkClickInsideTextView clickInterface;
#Override
public void onClick(View widget) {
getClickInterface().onLinkClicked(getText());
}
public void setText(String textString) {
this.text = textString;
}
public String getText() {
return this.text;
}
public void setClickInterface(HandleLinkClickInsideTextView clickInterface) {
this.clickInterface = clickInterface;
}
public HandleLinkClickInsideTextView getClickInterface() {
return this.clickInterface;
}
}
public interface HandleLinkClickInsideTextView {
public void onLinkClicked(String url);
}
After this i just used the method send click event.
textview.setText("http://google.com is google website and http://youtube.com is youtube site");
setLinkclickEvent(textview, new HandleLinkClickInsideTextView() {
public void onLinkClicked(String url) {
// Here I added my code
}
});
You can achieved the same using SpannableStringBuilder.
Simply initialize the TextView that you want to add 2 or more listeners and then pass that to the following method that I have created:
SAMPLE CODE:
private void customTextView(TextView view) {
SpannableStringBuilder spanTxt = new SpannableStringBuilder(
"I agree to the ");
spanTxt.append("Term of services");
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Terms of services Clicked",
Toast.LENGTH_SHORT).show();
}
}, spanTxt.length() - "Term of services".length(), spanTxt.length(), 0);
spanTxt.append(" and");
spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK), 32, spanTxt.length(), 0);
spanTxt.append(" Privacy Policy");
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Privacy Policy Clicked",
Toast.LENGTH_SHORT).show();
}
}, spanTxt.length() - " Privacy Policy".length(), spanTxt.length(), 0);
view.setMovementMethod(LinkMovementMethod.getInstance());
view.setText(spanTxt, BufferType.SPANNABLE);
}
And in your XML, use android:textColorLink to add custom link color of your choice. Like this:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColorLink="#C36241" />
If you want to open a link after textview click, there are two options:
Using java code:
Spanned text = Html.fromHtml("<u>GOOGLE.COM</u>");
textView.setText(text);
Uri uri = Uri.parse("http://shopwhere.com.au/");
Intent webIntent = new Intent(Intent.ACTION_VIEW,uri);
// Create and start the chooser
Intent chooser = Intent.createChooser(webIntent, "Open with");
startActivityForResult(chooser,0);
Using XML:
Use android:autoLink="web" inside textview tag. You can also change link color android:textColorHighlight="#android:color/transparent" and android:textColorLink="#color/white".

how to control textView onclicklistener with autolink web setting or in other words,intercept autolink web OnClick event?

How to control textView onclicklistener with autolink web setting or in other words,intercept autolink web OnClick event?
For example,String text="Lucy is very nice.Here is her link.https://www.google.com";textview.setText(text);
when clicking "https://www.google.com",I can catch it and jump to my app activity not to web browser.
Textview has a property “autolink”.I set autolink as web.android:autoLink="web" So,android system can automatically detect the url.When clicking the url,it will jump to the browser.Now when clicking, I do not want jump to the brower,I just want to jump to my app activity and stay in app.
Thanks you for all of your answers.Now I find my question's answer.There are two steps.
1.you need set Textview property. android:autoLink="web"
<TextView
android:id="#+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="Lucy is very nice.Here is her link.https://www.google.com" />
2.override URL onclick.There is an example.
public class MainActivity extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
CharSequence text = tv.getText();
if (text instanceof Spannable) {
int end = text.length();
Spannable sp = (Spannable) text;
URLSpan urls[] = sp.getSpans(0, end, URLSpan.class);
SpannableStringBuilder style = new SpannableStringBuilder(text);
style.clearSpans();
for (URLSpan urlSpan : urls) {
MyURLSpan myURLSpan = new MyURLSpan(urlSpan.getURL());
style.setSpan(myURLSpan, sp.getSpanStart(urlSpan),
sp.getSpanEnd(urlSpan),
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
tv.setText(style);
}
}
private class MyURLSpan extends ClickableSpan {
private String url;
public MyURLSpan(String url) {
this.url = url;
}
#Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
}
}
}
3.The above code perfectly solved my problem.So when I click www.google.com in the Textview,the url will show out and jump to a specific activity.
As your question is not clear I am giving you answer that might help.
Create another activity i which you want to show the link :
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_search);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString("message");
wv=(WebView)findViewById(R.id.left_webview);
getActionBar().setHomeButtonEnabled(true);
//wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setSupportMultipleWindows(true);
wv.loadUrl(url);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("URL :: " + url);
view.loadUrl(url);
return true;
}
});
}
in the textView activity :
Intent i = new Intent(TextViewActivity.this,NextActivity.class);
i.putExtra("message","https://google.com");
startActivity(i);
If I understand you question correctly this is what you are looking for. In order to control the click event on the text inside the TextView you have to use HTML to create the link and use a SpannableString.
// textView.setText("Lucy is very nice. Here is her link. https://www.google.com");
final String source = "Lucy is very nice. Here is her link. Click";
final Spanned html = Html.fromHtml(source);
final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(html);
final URLSpan[] spans = spannableStringBuilder.getSpans(0, html.length(), URLSpan.class);
final URLSpan span = spans[0];
final int start = spannableStringBuilder.getSpanStart(span);
final int end = spannableStringBuilder.getSpanEnd(span);
final int flags = spannableStringBuilder.getSpanFlags(span);
final ClickableSpan clickableSpan = new ClickableSpan() {
public void onClick(View view) {
Log.d(TAG, "Clicked: " + span.getURL());
}
};
spannableStringBuilder.setSpan(clickableSpan, start, end, flags);
spannableStringBuilder.removeSpan(span);
textView.setText(spannableStringBuilder);
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
EDIT
So, according to your comment you can't use HTML so here is another example taking the text from the TextView with autoLink already set:
final TextView textView = (TextView) findViewById(R.id.text);
final CharSequence text = textView.getText();
final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
final URLSpan[] spans = spannableStringBuilder.getSpans(0, text.length(), URLSpan.class);
final URLSpan span = spans[0];
final int start = spannableStringBuilder.getSpanStart(span);
final int end = spannableStringBuilder.getSpanEnd(span);
final int flags = spannableStringBuilder.getSpanFlags(span);
final ClickableSpan clickableSpan = new ClickableSpan() {
public void onClick(View view) {
Log.d(TAG, "Clicked: " + span.getURL());
}
};
spannableStringBuilder.setSpan(clickableSpan, start, end, flags);
spannableStringBuilder.removeSpan(span);
textView.setText(spannableStringBuilder);
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
I don't get what you are trying to say, but this will open a URL, or you can copy it to the cliopboard like copy and paste.
button.setOnClickListener((View.OnClickListener) v -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
}

How to make specific words' occurrences in a textview clickable

I need to make all the occurrences of a bunch of words, that I have in my textview text clickable
Eg. - I have 2 names in my arraylist - Ajay and Dhananjay
and lets say text in my textview is ........
#Ajay, #Dhananjay, I just had a great fight with #Vijay yesterday
now, I need to highlight only #Ajay and #Dhananjay all occurences in my textview, and make them clickable as well
but not #Vijay (as its not in my arraylist)
How to do so?
I run this code and worked fine for me, check it:
public class MainActivity extends AppCompatActivity {
TextView text;
String string = "#Ajay, #Dhananjay, I just had a great fight with #Vijay yesterday";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
SpannableString ss = new SpannableString(string);
String[] words = string.split(" ");
for (final String word : words) {
if (word.startsWith("#") && word.endsWith(",")) {
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
//use word here to make a decision
}
};
ss.setSpan(clickableSpan, string.indexOf(word), string.indexOf(word) + word.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
text.setText(ss);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
}
A few modifications in Survivor's Answer worked for me, as per my requirement.
text = (TextView) findViewById(R.id.textView1);
string += " ";
SpannableString ss = new SpannableString(string);
String[] words = string.split(" ");
for (final String word : words) {
if (word.startsWith("#") && mentionsNamesList.contains(word.substring(1))) {
int lastIndex = 0;
while(lastIndex != -1){
lastIndex = string.indexOf(word+" ",lastIndex);
if(lastIndex != -1){
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
//use word here to make a decision
}
};
ss.setSpan(clickableSpan, lastIndex, lastIndex + word.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
lastIndex += word.length();
}
}
}
text.setText(ss);
text.setMovementMethod(LinkMovementMethod.getInstance());
The modifications done included the use of while loop in order to highlight and make clickable every occurrence of the word in the whole textview,instead of only the first one. The other one was adding space along with the word to highlight, in order to avoid highlighting the substring occurrence within a bigger word. For eg. test in test123

Get the value of link text when clicked in a textview in android

I have a TextView. I have added custom links like "#abc", "#android" by matching some regex pattern. The links are displaying properly. However I am not getting a way to extract the text of the link which is clicked. I am using SpannableString to setText to the textview. I then set spans using my custom ClickableSpan. It works fine. Plus I can also catch the onclick event. But the onClick() method has a View paramter. If I call getText() on the View (ofcourse after typecasting it to TextView), it returns the entire text.
I searched a lot but always found ways to add links and catch the event, but none told about getting the text of the link.
This is the code I am using to add links and recieve onclick. I got the code from one of the SO threads..
Pattern pattern = Pattern.compile("#[\\w]+");
Matcher matcher = pattern.matcher(tv.getText());//tv is my TextView
while (matcher.find()) {
int x = matcher.start();
int y = matcher.end();
final android.text.SpannableString f = new android.text.SpannableString(
tv.getText());
f.setSpan(new InternalURLSpan(new View.OnClickListener() {
public void onClick(View v) {
showDialog(1);
}
}), x, y, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(f);
tv.setLinkTextColor(Color.rgb(19, 111, 154));
tv.setLinksClickable(true);
Here is the InternalURLSpan:
class InternalURLSpan extends android.text.style.ClickableSpan {
View.OnClickListener mListener;
public InternalURLSpan(View.OnClickListener listener) {
mListener = listener;
}
#Override
public void onClick(View widget) {
mListener.onClick(widget);
TextView tv = (TextView) widget;
System.out.println("tv.gettext() :: " + tv.getText());
Toast.makeText(MyActivity.this,tv.getText(),
Toast.LENGTH_SHORT).show();
}
}
Is it possible to get the text of the link clicked?
If not, is there a way of associating some data to a particular link and knowing which link gets clicked?
Any pointers.
Thanks
The solution goes like this -
Call setLinks() with you textview and the text to be added.
setLinks(textView, text);
setLinks() function is as -
void setLinks(TextView tv, String text) {
String[] linkPatterns = {
"([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])",
"#[\\w]+", "#[\\w]+" };
for (String str : linkPatterns) {
Pattern pattern = Pattern.compile(str);
Matcher matcher = pattern.matcher(tv.getText());
while (matcher.find()) {
int x = matcher.start();
int y = matcher.end();
final android.text.SpannableString f = new android.text.SpannableString(
tv.getText());
InternalURLSpan span = new InternalURLSpan();
span.text = text.substring(x, y);
f.setSpan(span, x, y,
android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(f);
// tv.setOnLongClickListener(span.l);
}
}
tv.setLinkTextColor(Color.BLUE);
tv.setLinksClickable(true);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setFocusable(false);
}
and the InternalURLSpan class goes like this -
class InternalURLSpan extends android.text.style.ClickableSpan {
public String text;
#Override
public void onClick(View widget) {
handleLinkClicked(text);
}
}
handleLinkClicked() is as -
public void handleLinkClicked(String value) {
if (value.startsWith("http")) { // handle http links
} else if (value.startsWith("#")) { // handle #links
} else if (value.startsWith("#")) { // handle #links
}
}
Here is a pretty simple solution I found to get the value of the link inside the TextView when the user clicks on it. In this case I'm using phone numbers and it works like a charm.
myTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myTextView.getSelectionStart()== -1 &&
myTextView.getSelectionEnd() == -1){
Toast.makeText(getApplicationContext(), "You clicked outside the link",
Toast.LENGTH_SHORT).show();
}
else {
int start = myTextView.getSelectionStart();
int end = myTextView.getSelectionEnd();
String selected = myTextView.getText().toString().substring(start, end);
Toast.makeText(getApplicationContext(),
"Clicked: " + selected,
Toast.LENGTH_SHORT).show();
}
}
});
Hope it helps.
Use
android:linksClickable="true"
android:autoLink="web"
textView.setMovementMethod(LinkMovementMethod.getInstance())

android dev how to underline and change color of word in string like a link color

I have a app that gets a string from a database and it sets to a label. Now i want that label to underline one word such as "This word should be underlined." and i want to be able to click on that underline word and get its value. So do i set it up before i send it to the database or after. Thanks for any help. I tried code below and each line is highlighted because of the for loop. please help
SpannableStringBuilder builder = new SpannableStringBuilder();
for(int i=0;i<ListClass.getLatestActivity().size();i++){
String myString = ListClass.getLatestActivity().get(i);
builder.append(myString);
String substringThatShouldBeClickable = myString.substring(0,myString.indexOf(' ')).trim();
MySpan span = new MySpan(substringThatShouldBeClickable);
span.setOnMySpanClickListener(mySpanOnClickListener);
int start = 0;
int end = builder.length();
builder.setSpan(span, start, end, 0);
builder.append("\n" + "\n") ;
}
RAInfo.setText(builder);
RAInfo.setMovementMethod(LinkMovementMethod.getInstance());
Ok, so there's a few things you'll need to do. They way to accomplish this is by using a span inside of the TextView.
First you'll need a class that extends ClickableSpan:
public class MySpan extends ClickableSpan {
public interface OnMySpanClickListener {
public void onMySpanClick(String tag);
}
private final String myData;
private OnMySpanClickListener mOnMySpanClickListener;
public MySpan(String tag) {
super();
if (tag == null) {
throw new NullPointerException();
}
myData = tag;
}
#Override
public void onClick(View widget) {
if (mOnMySpanClickListener != null) {
mOnMySpanClickListener.onMySpanClick(myData);
}
}
public OnMySpanClickListener getOnMySpanClickListener() {
return mOnMySpanClickListener;
}
public void setOnMySpanClickListener(OnMySpanClickListener onMySpanClickListener) {
mOnMySpanClickListener = onMySpanClickListener;
}
}
In your Activity, you'll set the text of the TextView like this:
String myString = getFromDatabase();
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(myString);
//You'll need to call the constructor for MySpan with only the value of the part
//of the string that you want to work with ("Bob" in the example), however you
//determine that.
String substringThatShouldBeClickable = getMySubstring(myString); //"Bob"
MySpan span = new MySpan(substringThatShouldBeClickable);
span.setOnMySpanClickListener(mySpanOnClickListener);
//start and end control the range of characters in the string that are clickable,
//so modify this part so it only underlines the characters you want clickable
int start = 0;
int end = bulider.length();
builder.setSpan(span, start, end, 0);
label.setText(builder);
label.setMovementMethod(LinkMovementMethod.getInstance());
Finally, you'll need a handler for the click events on the span:
MySpan.OnMySpanClickListener mySpanOnClickListener = new MySpan.OnMySpanClickListener() {
public void onMySpanClick(String tag) {
//Here is where you'll do your work with the value in the String "tag"
}
};
Hope this helps.

Categories

Resources