Android: Setting onClickListener to a Part of text in a TextView - Issue

前端 未结 7 2239
忘掉有多难
忘掉有多难 2021-01-03 23:57

I am trying to recognise hashtags in my TextView and make them clickable such that I can take the user to another View when they click on the Hashtag.

I managed to i

7条回答
  •  天涯浪人
    2021-01-04 00:46

    there is a way... after seeing your question i was just googling .. and i found this, i hope it will work...

    1. you can use android.text.style.ClickableSpan link

    SpannableString ss = new SpannableString("Hello World");
        ClickableSpan span1 = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                // do some thing
            }
        };
    
        ClickableSpan span2 = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                // do another thing
            }
        };
    
        ss.setSpan(span1, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(span2, 6, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
        textView.setText(ss);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    

    another way.. link

     TextView myTextView = new TextView(this);
        String myString = "Some text [clickable]";
        int i1 = myString.indexOf("[");
        int i2 = myString.indexOf("]");
        myTextView.setMovementMethod(LinkMovementMethod.getInstance());
        myTextView.setText(myString, BufferType.SPANNABLE);
        Spannable mySpannable = (Spannable)myTextView.getText();
        ClickableSpan myClickableSpan = new ClickableSpan()
        {
         @Override
         public void onClick(View widget) { /* do something */ }
        };
        mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    answer just copied from those link...

提交回复
热议问题