How to set the part of the text view is clickable

后端 未结 20 1391
无人共我
无人共我 2020-11-22 01:29

I have the text \"Android is a Software stack\". In this text i want to set the \"stack\" text is clickable. in the sense if you click on t

20条回答
  •  庸人自扰
    2020-11-22 02:07

    You can you this method to set the clickable value

    public void setClickableString(String clickableValue, String wholeValue, TextView yourTextView){
        String value = wholeValue;
        SpannableString spannableString = new SpannableString(value);
        int startIndex = value.indexOf(clickableValue);
        int endIndex = startIndex + clickableValue.length();
        spannableString.setSpan(new ClickableSpan() {
                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        super.updateDrawState(ds);
                                        ds.setUnderlineText(false); // <-- this will remove automatic underline in set span
                                    }
    
                                    @Override
                                    public void onClick(View widget) {
                                        // do what you want with clickable value
                                    }
                                }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        yourTextView.setText(spannableString);
        yourTextView.setMovementMethod(LinkMovementMethod.getInstance()); // <-- important, onClick in ClickableSpan won't work without this
    }
    

    This is how to use it:

    TextView myTextView = findViewById(R.id.myTextView);
    setClickableString("stack", "Android is a Software stack", myTextView);
    

提交回复
热议问题