Handles clicks on TextView links when using Linkify to search and set links within text

I have a TextView filled with text that I get from the server. I use Linkify to handle all link searches and to configure URLSpan, where necessary, throughout the addLinks method.

The problem is that the default behavior when a link is clicked opens it in a browser, I want to get a click link and process it myself.

I do not see any Linkify method that allows me to set "OnClick" or something like that.

Thanks for the help:)

+6
source share
3 answers

Ok, so I was able to set my own "OnClickListener" for TextView links. My solution was to copy Linkify into my project, name it CustomLinkify and just change its applyLink method:

From:

 private static final void applyLink(String url, int start, int end, Spannable text) { URLSpan span = new URLSpan(url); text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } 

To:

 private static final void applyLink(final String url, int start, int end, Spannable text) { URLSpan span = new URLSpan(url) { @Override public void onClick(View widget) { _onLinkClickListener.onLinkClicked(url); } }; text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } 

Where _onLinkClickListener is the new field that I set before using the new CustomLinkify .

I know that this is not a very elegant solution, and I prefer google to allow the installation of the listener through the native Linkify, but for me it is better than implementing my own Spannable logics (as suggested in other related questions).

I believe in Linkify code, and I think that from time to time I will check if any changes will be made to it, if so, of course, I will update CustomLinkify with the changes.

Hope this helps someone.

+10
source

I also find it tedious to implement custom Spannable logic in the application, and as a result we will create a library for this. See Textoo .

With Textoo this can be achieved as:

 TextView myTextView = Textoo .config((TextView) findViewById(R.id.my_text_view)) .linkifyEmailAddresses() .linkifyMapAddresses() .linkifyPhoneNumbers() .linkifyWebUrls() // or just .linkifyAll() .linkify(patternSettings, "internal://settings/") .linkify(patternGoogle, "http://www.google.ie/search2?q=", null, transformFilter) .linkify(patternGoogle, "http://www.google.ie/search3?q=", matchFilter, transformFilter) .addLinksHandler(new LinksHandler() { @Override public boolean onClick(View view, String url) { if ("internal://settings/location".equals(url)) { Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(locSettings); return true; } else { return false; } } }) .apply(); 

Just to share and hope that someone finds this useful.

+2
source

Maybe you should use WebView instead of TextView?

-4
source

Source: https://habr.com/ru/post/958923/


All Articles