How to implement a OnClick for a text/link which is in a TextView [closed]
-
21-12-2019 - |
سؤال
I have a TextView
where it contains a text, link and emailID
, as shown in the ScreenShot
:
I want to implement it such that when a user clicks on the link, it should open the browser and EmailId opens SendMail.
I can not opening the browser and send email, but I want to implement a click
functionality for only particular text
, that is, Link
and EmailID
in that TextView
, not for the entire TextView
.
Is this possible?
المحلول
You should use built-in linkify. Read this tutorial, easy to understand:
Linkify text link url in TextView text Android example
These post also may help you Android Linkify text - Spannable Text in Single Text View - As like Twitter tweet
and Android: ClickableSpan in clickable TextView
And here is complete code using Spannable :
final String webAddress = "www.123456.org";
final String emailAddress = "info@123456.com";
TextView text = (TextView)findViewById(R.id.textview);
Spannable span = Spannable.Factory.getInstance().newSpannable("For more details on the app visit us at " + webAddress + " or write to us at " + emailAddress);
ClickableSpan webClickSpan = new ClickableSpan() {
@Override
public void onClick(View v) {
Uri uriUrl = Uri.parse("http://" + webAddress);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
} };
ClickableSpan emailClickSpan = new ClickableSpan() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailAddress});
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "email body.");
startActivity(Intent.createChooser(intent, "Send Email"));
} };
span.setSpan(webClickSpan, 40, 40 + webAddress.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(emailClickSpan, 73, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText(span);
text.setMovementMethod(LinkMovementMethod.getInstance());
نصائح أخرى
Use the Class Linkify:
Linkify.addLinks(yourTextView, Linkify.ALL);
or just for URLs:
Linkify.addLinks(yourTextView, Linkify.WEB_URLS);
It is achievable through a Spannable
object. Spannable
allows you to add markups to a portion of text and also, to attach a ClickableSpan
, that will be fired when you press on the span.