I have a TextView which could potentially contain a clickable link. I want to add a click listener to the TextView but still when a link is clicked, I want it to be handled normally by Linkify.
It took me a while to figure this out and I wanted to share the answer since it's been working well so, enjoy!
This code traverses the string by separating characters at the space character: " ".
It then checks each 'word' for a link.
TextView textView = new TextView(context) {
#Override
public boolean onTouchEvent(MotionEvent event) {
final String text = getText().toString();
final SpannableString spannableString = new SpannableString(text);
Linkify.addLinks(spannableString, Linkify.ALL);
final URLSpan[] spans = spannableString.getSpans(0, text.length(), URLSpan.class);
final int indexOfCharClicked = getOffsetForPosition(event.getX(), event.getY()) + 1; //Change 0-index to 1-index
final String [] words = text.split(" ");
int numCharsTraversed = 0;
//Find the word that was clicked and check if it's a link
for (String word : words) {
if (numCharsTraversed + word.length() < indexOfCharClicked) {
numCharsTraversed += word.length() + 1; // + 1 for the space
} else {
for (URLSpan span : spans) {
if (span.getURL().contains(word) || word.contains(span.getURL())) {
//If the clicked word is a link, calling super will invoke the appropriate action
return super.onTouchEvent(event);
}
}
break;
}
}
//If we're here, it means regular text was clicked, not a link
doSomeAction();
return true;
}
};
I have 2 edittexts and 1 textview. 1 edittext for input the price another one the percentage and the textview will display the result of them both (the price * percentage/100) and i want to make the 1st edittext input(for the price) will change the format of the input and display it on the same edittext with decimal format. For example :
edittext1
100
the user type 100 it will just display 100 ,but when the user type one or more number(S) it will add "," every 3 number
edittext1
1,000
edittext1
10,000
edittext1
100,000
edittext1
1,000,000
and so on
i have the functions, one will autocalculate the value for textview1 , another will convert automatically the input of edittext. However they cant work together because the format for calculation function, it uses int/long/double and for the converter it uses decimalformat . If i use them both the app will crash with javanumberformatexception unable to parse int "1,000"(if we put 1000 into edittext)
my function for autocalculate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simulasikredit);
ethint1 = (EditText) findViewById(R.id.ethint);
etpersen2 = (EditText) findViewById(R.id.etpersen);
textvDP1 = (TextView) findViewById(R.id.textvDP);
etpersen2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text1 = ethint1.getText().toString();
String text2 = etpersen2.getText().toString();
long input1 = 0;
long input2 = 0;
if(text1.length()>0)
input1 = Long.valueOf(text1);
if(text2.length()>0)
input2 = Long.valueOf(text2);
if (text1.length() != 0) {
long output = (input1 * input2) / 100;
textvDP1.setText(""+output);
}
else if(text2.length() == 0){
textvDP1.setText("");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
}); }
et stands for edittext, tv stands for textview
and makedecimal function
public void makedecimal(View v)
{
ethint1.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
DigitsKeyListener dkl = new DigitsKeyListener(true,true);
ethint1.setKeyListener(dkl);
ethint1.addTextChangedListener(new TextWatcher(){
private String current = "";
#Override
public void afterTextChanged(Editable s) {
String userInput=s.toString();
if(!userInput.toString().equals(current)){
ethint1.removeTextChangedListener(this);
String cleanString = userInput.replaceAll("[,]", "");
if(cleanString.length()>0){
double parsed = Double.parseDouble(cleanString);
String formated = DecimalFormat.getNumberInstance().format(parsed);
current = formated;
ethint1.setText(formated);
ethint1.setSelection(formated.length());
}else{
ethint1.setText(cleanString);
ethint1.setSelection(cleanString.length());
}
ethint1.addTextChangedListener(this);
}
this makedecimal is android:onClick from ethint , ethint is the id(these two come from 1 edittext)
I need to fulfil a similar requirements before where we need to format the number in thousands and also support fractions.
My approach is to register a TextWatcher format text every time input changed, and provide a public method to get numeric value by stripping separators, which is quite tricky. My solution also caters for locale-specific separator by utilizing DecimalFormatSymbols class.
private final char GROUPING_SEPARATOR = DecimalFormatSymbols.getInstance().getGroupingSeparator();
private final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
...
/**
* Return numeric value repesented by the text field
* #return numeric value or {#link Double.NaN} if not a number
*/
public double getNumericValue() {
String original = getText().toString().replaceAll(mNumberFilterRegex, "");
if (hasCustomDecimalSeparator) {
// swap custom decimal separator with locale one to allow parsing
original = StringUtils.replace(original,
String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR));
}
try {
return NumberFormat.getInstance().parse(original).doubleValue();
} catch (ParseException e) {
return Double.NaN;
}
}
/**
* Add grouping separators to string
* #param original original string, may already contains incorrect grouping separators
* #return string with correct grouping separators
*/
private String format(final String original) {
final String[] parts = original.split("\\" + mDecimalSeparator, -1);
String number = parts[0] // since we split with limit -1 there will always be at least 1 part
.replaceAll(mNumberFilterRegex, "")
.replaceFirst(LEADING_ZERO_FILTER_REGEX, "");
// only add grouping separators for non custom decimal separator
if (!hasCustomDecimalSeparator) {
// add grouping separators, need to reverse back and forth since Java regex does not support
// right to left matching
number = StringUtils.reverse(
StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR));
// remove leading grouping separator if any
number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR));
}
// add fraction part if any
if (parts.length > 1) {
number += mDecimalSeparator + parts[1];
}
return number;
}
It's quite tedious to elaborate here so I'll only give a link for your own reading:
https://gist.github.com/hidroh/77ca470bbb8b5b556901
I've been stuck at this problem for long. What I'm having is a simple string "This is a link and this is another link". I want to have both "link" words click-able, having different URLs to open in browser.
The simplest way I can do is to set Click-able Span on both "link"
words with different URLs, but the problem I'm facing is finding the
start and end positions of the span. The text is dynamic, and I have
to programmatically find the positions.
One approach would be to find the first occurrence of the word
'link', find the start and end positions and set the span, and then
the second occurrence. But that is not reliable. The text may contain
more than one kind of repeated words, like "This is a cat link and
this is another cat link". Here I have to link both "cat" and "link"
words with different URLs via Click-able Span. How do I go about it?
Try in this manner
String s="Cat link 1 Cat link 2 Cat link 3";
SpannableString ss = new SpannableString(s);
String first ="Cat link 1";
String second ="Cat link 2";
String third ="Cat link 3";
int firstIndex = s.toString().indexOf(first);
int secondIndex = s.toString().indexOf(second);
ClickableSpan firstwordClick = new ClickableSpan() {
#Override
public void onClick(View widget) {
///............
}
};
ClickableSpan secondwordClick = new ClickableSpan() {
#Override
public void onClick(View widget) {
///............
}
};
ss.setSpan(firstwordClick,firstIndex, firstIndex+first.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(secondwordClick,secondIndex, secondIndex+second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(ss,BufferType.SPANNABLE);
If you cannot programmatically find the difference in the links, then you cannot expect anything else to be able to do it. As the developer, you need a system.
You need to be able to identify the clickable spans - since the links are unique, the text that identifies them must also be unique. This would be a problem for your users, most likely.
You can get an ordered list of URLs and then if the links are indistinguishable, simply use them in the order you receive. Or, you need to change the rules of creating the links or the order in which they are displayed.
One simple way to do this would be to include an identifier before the link say /*/ then using this find the start and end position for link. Once you have that first replace the identifier with a "" and then click away.
I have string something such "you order with orderId {b1j2gh4b} has been claimed by bla bla sotre with phone number (1234124124)"
I am using these braces so as to find out the index of of orderID and Phone number
String notificationMessage = mArrListNotification.get(position).getMessage();
boolean isPhoneNumberAvailable = false, isOrderIdAvailable = false;
int phoneStartIndex = 0, phoneEndIndex = 0, orderIdStartIndex = 0, orderIdEndIndex = 0;
//getting index on the basis of braces added to text
if (notificationMessage.contains("(")) {
isPhoneNumberAvailable = true;
phoneStartIndex = notificationMessage.indexOf("(");
phoneEndIndex = notificationMessage.indexOf(")");
}
if (notificationMessage.contains("{")) {
orderIdStartIndex = notificationMessage.indexOf("{");
orderIdEndIndex = notificationMessage.indexOf("}");
}
// we got the index so remove braces
notificationMessage = notificationMessage.replace("(", " ");
notificationMessage = notificationMessage.replace(")", " ");
notificationMessage = notificationMessage.replace("{", " ");
notificationMessage = notificationMessage.replace("}", " ");
viewHolder.txtNotificationMessage.setText(notificationMessage, TextView.BufferType.SPANNABLE);
Spannable mySpannablePhoneNumber = (Spannable) viewHolder.txtNotificationMessage.getText();
Spannable mySpannableOrderID = (Spannable) viewHolder.txtNotificationMessage.getText();
ClickableSpan mySpanPhoneClick = new ClickableSpan() {
#Override
public void onClick(View widget) {
currentPosition = (Integer) widget.getTag();
String message = mArrListNotification.get(currentPosition).getMessage();
int startIndex = message.indexOf("(");
int endIndex = message.indexOf(")");
phoneNumber = message.substring(startIndex + 1, endIndex);
Log.i("Phone Number", phoneNumber clicked)
}
};
ClickableSpan mySpanOrderClick = new ClickableSpan() {
#Override
public void onClick(View widget) {
currentPosition = (Integer) widget.getTag();
String message = mArrListNotification.get(currentPosition).getMessage();
int startIndex = message.indexOf("{");
int endIndex = message.indexOf("}");
String orderID = message.substring(startIndex + 1, endIndex);
// Log.i("Order id", orderID clicked)
}
};
if (isPhoneNumberAvailable) {
mySpannablePhoneNumber.setSpan(mySpanPhoneClick, phoneStartIndex + 1, phoneEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (isOrderIdAvailable) {
mySpannableOrderID.setSpan(mySpanOrderClick, orderIdStartIndex + 1, orderIdEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
I have a TextView which is rendering basic HTML, containing 2+ links. I need to capture clicks on the links and open the links -- in my own internal WebView (not in the default browser.)
The most common method to handle link rendering seems to be like this:
String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setLinksClickable(true);
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );
However, this causes the links to open in the default internal web browser (showing the "Complete Action Using..." dialog).
I tried implementing a onClickListener, which properly gets triggered when the link is clicked, but I don't know how to determine WHICH link was clicked...
text_view.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// what now...?
}
});
Alternatively, I tried creating a custom LinkMovementMethod class and implementing onTouchEvent...
public boolean onTouchEvent(TextView widget, Spannable text, MotionEvent event) {
String url = text.toString();
// this doesn't work because the text is not necessarily a URL, or even a single link...
// eg, I don't know how to extract the clicked link from the greater paragraph of text
return false;
}
Ideas?
Example solution
I came up with a solution which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL.
Based upon another answer, here's a function setTextViewHTML() which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL.
protected 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) {
// Do something with span.getURL() to handle the link click...
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setTextViewHTML(TextView text, String html)
{
CharSequence sequence = Html.fromHtml(html);
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());
}
I made an easy extension function in Kotlin to catch url link clicks in a TextView by applying a new callback to URLSpan elements.
strings.xml (example link in text)
<string name="link_string">this is my link: CLICK</string>
Make sure your spanned text is set to the TextView before you call "handleUrlClicks"
textView.text = getString(R.string.link_string)
This is the extension function:
/**
* Searches for all URLSpans in current text replaces them with our own ClickableSpans
* forwards clicks to provided function.
*/
fun TextView.handleUrlClicks(onClicked: ((String) -> Unit)? = null) {
//create span builder and replaces current text with it
text = SpannableStringBuilder.valueOf(text).apply {
//search for all URL spans and replace all spans with our own clickable spans
getSpans(0, length, URLSpan::class.java).forEach {
//add new clickable span at the same position
setSpan(
object : ClickableSpan() {
override fun onClick(widget: View) {
onClicked?.invoke(it.url)
}
},
getSpanStart(it),
getSpanEnd(it),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
//remove old URLSpan
removeSpan(it)
}
}
//make sure movement method is set
movementMethod = LinkMovementMethod.getInstance()
}
This is how I call it:
textView.handleUrlClicks { url ->
Timber.d("click on found span: $url")
}
You've done as follows:
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );
have you tried in reverse order as shown below?
text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(LinkMovementMethod.getInstance());
and without:
text_view.setLinksClickable(true);
This can be simply solved by using Spannable String.What you really want to do (Business Requirement) is little bit unclear to me so following code will not give exact answer to your situation but i am petty sure that it will give you some idea and you will be able to solve your problem based on the following code.
As you do, i'm also getting some data via HTTP response and i have added some additional underlined text in my case "more" and this underlined text will open the web browser on click event.Hope this will help you.
TextView decription = (TextView)convertView.findViewById(R.id.library_rss_expan_chaild_des_textView);
String dec=d.get_description()+"<a href='"+d.get_link()+"'><u>more</u></a>";
CharSequence sequence = Html.fromHtml(dec);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
UnderlineSpan[] underlines = strBuilder.getSpans(0, 10, UnderlineSpan.class);
for(UnderlineSpan span : underlines) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan myActivityLauncher = new ClickableSpan() {
public void onClick(View view) {
Log.e(TAG, "on click");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(d.get_link()));
mContext.startActivity(intent);
}
};
strBuilder.setSpan(myActivityLauncher, start, end, flags);
}
decription.setText(strBuilder);
decription.setLinksClickable(true);
decription.setMovementMethod(LinkMovementMethod.getInstance());
I've had the same problem but a lot of text mixed with few links and emails.
I think using 'autoLink' is a easier and cleaner way to do it:
text_view.setText( Html.fromHtml( str_links ) );
text_view.setLinksClickable(true);
text_view.setAutoLinkMask(Linkify.ALL); //to open links
You can set Linkify.EMAIL_ADDRESSES or Linkify.WEB_URLS if there's only one of them
you want to use or set from the XML layout
android:linksClickable="true"
android:autoLink="web|email"
The available options are:
none, web, email, phone, map, all
Solution
I have implemented a small class with the help of which you can handle long clicks on TextView itself and Taps on the links in the TextView.
Layout
TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"/>
TextViewClickMovement.java
import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;
public class TextViewClickMovement extends LinkMovementMethod {
private final String TAG = TextViewClickMovement.class.getSimpleName();
private final OnTextViewClickMovementListener mListener;
private final GestureDetector mGestureDetector;
private TextView mWidget;
private Spannable mBuffer;
public enum LinkType {
/** Indicates that phone link was clicked */
PHONE,
/** Identifies that URL was clicked */
WEB_URL,
/** Identifies that Email Address was clicked */
EMAIL_ADDRESS,
/** Indicates that none of above mentioned were clicked */
NONE
}
/**
* Interface used to handle Long clicks on the {#link TextView} and taps
* on the phone, web, mail links inside of {#link TextView}.
*/
public interface OnTextViewClickMovementListener {
/**
* This method will be invoked when user press and hold
* finger on the {#link TextView}
*
* #param linkText Text which contains link on which user presses.
* #param linkType Type of the link can be one of {#link LinkType} enumeration
*/
void onLinkClicked(final String linkText, final LinkType linkType);
/**
*
* #param text Whole text of {#link TextView}
*/
void onLongClick(final String text);
}
public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
}
#Override
public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {
mWidget = widget;
mBuffer = buffer;
mGestureDetector.onTouchEvent(event);
return false;
}
/**
* Detects various gestures and events.
* Notify users when a particular motion event has occurred.
*/
class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent event) {
// Notified when a tap occurs.
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// Notified when a long press occurs.
final String text = mBuffer.toString();
if (mListener != null) {
Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Text: " + text + "\n<----");
mListener.onLongClick(text);
}
}
#Override
public boolean onSingleTapConfirmed(MotionEvent event) {
// Notified when tap occurs.
final String linkText = getLinkText(mWidget, mBuffer, event);
LinkType linkType = LinkType.NONE;
if (Patterns.PHONE.matcher(linkText).matches()) {
linkType = LinkType.PHONE;
}
else if (Patterns.WEB_URL.matcher(linkText).matches()) {
linkType = LinkType.WEB_URL;
}
else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
linkType = LinkType.EMAIL_ADDRESS;
}
if (mListener != null) {
Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Link Text: " + linkText + "\n" +
"Link Type: " + linkType + "\n<----");
mListener.onLinkClicked(linkText, linkType);
}
return false;
}
private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
return buffer.subSequence(buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0])).toString();
}
return "";
}
}
}
Usage
String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(new TextViewClickMovement(this, context));
Links
Hope this helops! You can find code here.
A way cleaner and better solution, using native's Linkify library.
Example:
Linkify.addLinks(mTextView, Linkify.ALL);
If you're using Kotlin, I wrote a simple extension for this case:
/**
* Enables click support for a TextView from a [fullText] String, which one containing one or multiple URLs.
* The [callback] will be called when a click is triggered.
*/
fun TextView.setTextWithLinkSupport(
fullText: String,
callback: (String) -> Unit
) {
val spannable = SpannableString(fullText)
val matcher = Patterns.WEB_URL.matcher(spannable)
while (matcher.find()) {
val url = spannable.toString().substring(matcher.start(), matcher.end())
val urlSpan = object : URLSpan(fullText) {
override fun onClick(widget: View) {
callback(url)
}
}
spannable.setSpan(urlSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
text = spannable
movementMethod = LinkMovementMethod.getInstance() // Make link clickable
}
Usage:
yourTextView.setTextWithLinkSupport("click on me: https://www.google.fr") {
Log.e("URL is $it")
}
An alternative, imho way simpler approach (for lazy developers like myself ;)
abstract class LinkAwareActivity : AppCompatActivity() {
override fun startActivity(intent: Intent?) {
if(Intent.ACTION_VIEW.equals(intent?.action) && onViewLink(intent?.data.toString(), intent)){
return
}
super.startActivity(intent)
}
// return true to consume the link (meaning to NOT call super.startActivity(intent))
abstract fun onViewLink(url: String?, intent: Intent?): Boolean
}
If required, you could also check for scheme / mimetype of the intent
You can do it more neatly using a simple library named Better-Link-Movement-Method.
TextView mTvUrl=findViewById(R.id.my_tv_url);
mTvUrl.setMovementMethod(BetterLinkMovementMethod.newInstance().setOnLinkClickListener((textView, url) -> {
if (Patterns.WEB_URL.matcher(url).matches()) {
//An web url is detected
return true;
}
else if(Patterns.PHONE.matcher(url).matches()){
//A phone number is detected
return true;
}
else if(Patterns.EMAIL_ADDRESS.matcher(url).matches()){
//An email address is detected
return true;
}
return false;
}));
Im using only textView, and set span for url and handle click.
I found very elegant solution here, without linkify - according to that I know which part of string I want to linkify
handle textview link click in my android app
in kotlin:
fun linkify(view: TextView, url: String, context: Context) {
val text = view.text
val string = text.toString()
val span = ClickSpan(object : ClickSpan.OnClickListener {
override fun onClick() {
// handle your click
}
})
val start = string.indexOf(url)
val end = start + url.length
if (start == -1) return
if (text is Spannable) {
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
text.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
} else {
val s = SpannableString.valueOf(text)
s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
s.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
view.text = s
}
val m = view.movementMethod
if (m == null || m !is LinkMovementMethod) {
view.movementMethod = LinkMovementMethod.getInstance()
}
}
class ClickSpan(private val mListener: OnClickListener) : ClickableSpan() {
override fun onClick(widget: View) {
mListener.onClick()
}
interface OnClickListener {
fun onClick()
}
}
and usage: linkify(yourTextView, urlString, context)
This page solved my problem, but I had to figure something out myself. I was using android string resources to set the text of the TextView and obviously, they returned a CharSequence that has a link in between the text.
These were the resources:
<string name="license_agreement">By registering, you agree with our <b>Privacy Policy</b> and <b>Terms and Conditions</b></string>
<string name="sign_now">Already have an account? <b>Login</b></string>
I made changes to one of the code suggested. The code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Make Licence agreement statements and login text clickable links
setLinkOnText(binding.txtLcAgree);
setLinkOnText(binding.signNow);
}
private void detectLinkClick(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) {
// Do something with links retrieved from span.getURL(), to handle link click...
String clickedUrl = span.getURL();
switch (clickedUrl) {
case "#login_page":
startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
break;
case "http://www.privacy-options.com":
Uri link1 = Uri.parse("http://www.privacy-options.com");
startActivity(new Intent(Intent.ACTION_VIEW, link1));
break;
case "http://www.terms-and-conditions.com":
Uri link2 = Uri.parse("http://www.terms-and-conditions.com");
startActivity(new Intent(Intent.ACTION_VIEW, link2));
break;
default:
Log.w(getClass().getSimpleName(), "No action for this");
}
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setLinkOnText(TextView text) {
CharSequence sequence = text.getText();
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for (URLSpan span : urls) {
detectLinkClick(strBuilder, span);
}
text.setText(strBuilder);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
The links retrieved from span.getUrl() was the initial link I set in the string resource. And since the text in the TextView was already in link format, I just simply used that text in the SpannableStringBuilder.
For The amazing answer by Zane Claes on top. Simply add the below code before calling strBuilder.getSpans() works great for me.
Linkify.addLinks(strBuilder, Linkify.ALL)
You need to create a class that extends LinkMovementMethod and override the onTouchEvent() function. I duplicated some code from LinkMovementMethod's method to get the link.
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] links = buffer.getSpans(off, off, ClickableSpan.class);
if (links.length != 0) {
String url = ((URLSpan) links[0]).getURL());
} else {
return super.onTouchEvent(widget, buffer, event);
}
}
return super.onTouchEvent(widget, buffer, event);
}
Is there any way I can launch an activity from a portion of a string.
eg
I have this in my strings.xml file:
<string name="clickable_string">This is a <u>clickable string</u></string>
I would like the text between the u tags to be underlined and launch an activity when clicked when inserted in to a TextView
Try this,
final Context context = ... // whereever your context is
CharSequence sequence = Html.fromSource(context.getString(R.string.clickable_string));
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
UnderlineSpan[] underlines = strBuilder.getSpans(UnderlineSpan.class);
for(UnderlineSpan span : underlines) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan myActivityLauncher = new ClickableSpan() {
public void onClick(View view) {
context.startActivity(getIntentForActivityToStart());
}
};
strBuilder.setSpan(myActivityLauncher, start, end, flags);
}
TextView textView = ...
textView.setText(strBuilder);
textView.setMovementMethod(LinkMovementMethod.getInstance());
Basically you have to attach a Span object to the range of characters you want to be clickable. Since you are using HTML anyways, you can use the underline spans placed by the Html.fromSource() as markers for your own spans.
Alternatively you could also define a Tag within the string that only you know of.
i.e. <activity>
And supply your own tag handler to the Html.fromSource() method. This way your TagHandler instance could do something like, surround the tagged text with a specific color, underline, bold and make it clickable. However I would only recommend the TagHandler approach if you find yourself writing this type of code a lot.
assign this string to one of your xml layout and then in your code get the id of TextView and then implement OnClickListener for this Textview,inside of it you can start your new activity you want.
Answered here Make parts of textview clickable (not url)
I just made a modification if you want to use it with a HTML Message do the following
In your Display function
public void displayText(String message) {
chapterTextView.setText(Html.fromHtml(message),TextView.BufferType.SPANNABLE);
chapterTextView.setMovementMethod(LinkMovementMethod.getInstance());
Spannable clickableMessage = (Spannable) chapterTextView.getText();
chapterTextView.setText(addClickablePart(clickableMessage), BufferType.SPANNABLE);
}
The Modified function of addClickablePart
private SpannableStringBuilder addClickablePart(Spannable charSequence) {
SpannableStringBuilder ssb = new SpannableStringBuilder(charSequence);
int idx1 = charSequence.toString().indexOf("(");
int idx2 = 0;
while (idx1 != -1) {
idx2 = charSequence.toString().indexOf(")", idx1) + 1;
final String clickString = charSequence.toString().substring(idx1, idx2);
ssb.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getActivity(), clickString,
Toast.LENGTH_SHORT).show();
}
}, idx1, idx2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
idx1 = charSequence.toString().indexOf("(", idx2);
}
return ssb;
}
Hope this help someone.