How to set the part of the text view is clickable

后端 未结 20 1034
无人共我
无人共我 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:12

    I made this helper method in case someone need start and end position from a String.

    public static TextView createLink(TextView targetTextView, String completeString,
        String partToClick, ClickableSpan clickableAction) {
    
        SpannableString spannableString = new SpannableString(completeString);
    
        // make sure the String is exist, if it doesn't exist
        // it will throw IndexOutOfBoundException
        int startPosition = completeString.indexOf(partToClick);
        int endPosition = completeString.lastIndexOf(partToClick) + partToClick.length();
    
        spannableString.setSpan(clickableAction, startPosition, endPosition,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        targetTextView.setText(spannableString);
        targetTextView.setMovementMethod(LinkMovementMethod.getInstance());
    
        return targetTextView;
    }
    

    And here is how you use it

    private void initSignUp() {
        String completeString = "New to Reddit? Sign up here.";
        String partToClick = "Sign up";
        ClickableTextUtil
            .createLink(signUpEditText, completeString, partToClick,
                new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        // your action
                        Toast.makeText(activity, "Start Sign up activity",
                            Toast.LENGTH_SHORT).show();
                    }
    
                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        // this is where you set link color, underline, typeface etc.
                        int linkColor = ContextCompat.getColor(activity, R.color.blumine);
                        ds.setColor(linkColor);
                        ds.setUnderlineText(false);
                    }
                });
    }
    

提交回复
热议问题