Android Multiple clickable strings in textview

后端 未结 1 2046
走了就别回头了
走了就别回头了 2021-01-17 18:01

I am creating a small Android app. I would like to display a text in a textview with multiple parts to click on. (Each should show some different message)

Finally I

相关标签:
1条回答
  • 2021-01-17 18:01

    as i understand you want to make multiple part of textview clickable.

    this code worked for me!

    SpannableString ss = new SpannableString("this is a text");
    ss.setSpan(new myClickableSpan(1),0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new myClickableSpan(2),5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new myClickableSpan(3),8, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    mTextView.setText(ss);
    mTextView.setMovementMethod(LinkMovementMethod.getInstance());
    

    just make custom ClickableSpan to handle the click event

    public class myClickableSpan extends ClickableSpan{
    
        int pos;
        public myClickableSpan(int position){
            this.pos=position;
        }
    
        @Override
        public void onClick(View widget) {
            Toast.makeText(getApplicationContext(), "Position "  + pos + " clicked!", Toast.LENGTH_LONG).show();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题