Android: Launch activity from clickable text

前端 未结 3 513
臣服心动
臣服心动 2020-11-28 06:23

Is there any way I can launch an activity from a portion of a string.

eg I have this in my strings.xml file:



        
3条回答
  •  忘掉有多难
    2020-11-28 07:05

    Answered here Make parts of textview clickable (not url) I just made a modification if you want to use it with a HTML Message do the following In your Display function

    public void displayText(String message) {
    
                chapterTextView.setText(Html.fromHtml(message),TextView.BufferType.SPANNABLE);
                chapterTextView.setMovementMethod(LinkMovementMethod.getInstance());
                Spannable clickableMessage = (Spannable) chapterTextView.getText();
                chapterTextView.setText(addClickablePart(clickableMessage), BufferType.SPANNABLE);
    }
    

    The Modified function of addClickablePart

    private SpannableStringBuilder  addClickablePart(Spannable charSequence) {
            SpannableStringBuilder  ssb = new SpannableStringBuilder(charSequence);
    
            int idx1 = charSequence.toString().indexOf("(");
            int idx2 = 0;
            while (idx1 != -1) {
                idx2 = charSequence.toString().indexOf(")", idx1) + 1;
    
                final String clickString = charSequence.toString().substring(idx1, idx2);
                ssb.setSpan(new ClickableSpan() {
    
                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(getActivity(), clickString,
                                Toast.LENGTH_SHORT).show();
                    }
                }, idx1, idx2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                idx1 = charSequence.toString().indexOf("(", idx2);
            }
    
            return ssb;
        }
    

    Hope this help someone.

提交回复
热议问题