How to handle link click events in a textView

2k views Asked by At

I am using Jsoup to parse the a website, formatting it with Html.fromHtml()and displaying the formatted text in a textview.

Also, I'm using LinkMoveMentmethod.getInstance to make the links in the textview clickable.

When the links are clicked they fired up a chooser to choose browsers.

Please, how can I override this default behaviour.

For example, I would want to pass the clicked url to my own activity and use Jsoup to parse it also.


CODE

TextView pageContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_details);
        getWindow().getDecorView().setBackgroundColor(Color.WHITE);
        pageContent = (TextView) findViewById(R.id.dpage_content);
}
....

private void parseHtml(String response) {
        Log.d(TAG, "parsinghtml");
        Document document = Jsoup.parse(response);
        page_content = document.select("div.page-content").first().html();

        Spanned spanned = Html.fromHtml(page_content, new UILImageGetter(pageContent, this), null );
    }
2

There are 2 answers

2
Rajen Raiyarela On

You need to create your custom class which extends LinkMovementMethod.

public class LinkClickHandler extends LinkMovementMethod{
    private static LinkClickHandler sInstance;

    public static LinkClickHandler getInstance() {
        if (sInstance == null)
            sInstance = new LinkClickHandler();
        return sInstance;
    }

    @Override
    public boolean onTouchEvent(TextView widget, 
            Spannable buffer, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP) {
             //Implement your code for handling the click.
        }
         return super.onTouchEvent(widget, buffer, event);
    }
}

To use this, change LinkMovementMethod.getInstance to LinkClickHandler.getInstance

6
Jitu On

You can use clickable span

     ClickableSpan cs = new ClickableSpan() {  
   @Override
     public void onClick(View v) {  
      Log.d("main", "textview clicked");
        Toast.makeText(Main.this, "textview clicked",Toast.LENGTH_SHORT).show(); 
      } };
     // set the "test " spannable.
     span.setSpan(cs, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(span);
  tv.setMovementMethod(LinkMovementMethod.getInstance());