Multiple Clickable links in TextView on Android

后端 未结 8 748
无人共我
无人共我 2020-12-14 07:16

I\'m trying to add multiple links in a textview similar to what Google & Flipboard has done below with their Terms and conditions AND Privacy Po

8条回答
  •  萌比男神i
    2020-12-14 08:12

    I think that I'm a little late to share this, but I have achieved the same using SpannableStringBuilder.

    Simply initialize the TextView that you want to add 2 or more listeners and then pass that to the following method that I have created:

    private void customTextView(TextView view) {
            SpannableStringBuilder spanTxt = new SpannableStringBuilder(
                    "I agree to the ");
            spanTxt.append("Term of services");
            spanTxt.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Toast.makeText(getApplicationContext(), "Terms of services Clicked",
                            Toast.LENGTH_SHORT).show();
                }
            }, spanTxt.length() - "Term of services".length(), spanTxt.length(), 0);
            spanTxt.append(" and");
            spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK), 32, spanTxt.length(), 0);
            spanTxt.append(" Privacy Policy");
            spanTxt.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Toast.makeText(getApplicationContext(), "Privacy Policy Clicked",
                            Toast.LENGTH_SHORT).show();
                }
            }, spanTxt.length() - " Privacy Policy".length(), spanTxt.length(), 0);
            view.setMovementMethod(LinkMovementMethod.getInstance());
            view.setText(spanTxt, BufferType.SPANNABLE);
        } 
    

    And in your XML, use android:textColorLink to add custom link color of your choice. Like this:

         //#C36241 - Rust
    

    And this looks like this:

    enter image description here

    Hope it helps someone. :)

提交回复
热议问题