Search code examples
javaandroidkotlinandroid-layouttextview

Multiple Clickable links in TextView on Android


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 Policy shown in the screen shot below:

So far I've stumbled on using this approach

textView.setText(Html.fromHtml(myHtml); textView.setMovementMethod(LinkMovementMethod.getInstance());

where myHtml is a href.

But it doesn't give me control I need e.g to launch a fragment etc.

Any idea how they achieve this in the two examples below?

Flipboard terms and conditions view

Google terms and conditions view


Solution

  • You can use Linkify (android.text.Spannable,java.util.regex.Pattern,java.lang.String)

    String termsAndConditions = getResources().getString(R.string.terms_and_conditions);
    String privacyPolicy = getResources().getString(R.string.privacy_policy);
    
    legalDescription.setText(
        String.format(
            getResources().getString(R.string.message),
            termsAndConditions,
            privacyPolicy)
    );
    legalDescription.setMovementMethod(LinkMovementMethod.getInstance());
    
    Pattern termsAndConditionsMatcher = Pattern.compile(termsAndConditions);
    Linkify.addLinks(legalDescription, termsAndConditionsMatcher, "terms:");
    
    Pattern privacyPolicyMatcher = Pattern.compile(privacyPolicy);
    Linkify.addLinks(legalDescription, privacyPolicyMatcher, "privacy:");
    

    and then you can use the scheme to start an activity for example by adding the scheme in the AndroidManifest:

    <intent-filter>
        <category android:name="android.intent.category.DEFAULT" />
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="terms" />
        <data android:scheme="privacy" />
    </intent-filter>
    

    If you want to do a custom action, you can set the intent-filter to your current activity, which will have a singleTop launchmode.

    This will cause onNewIntent to be fired where can make your custom actions:

    @Override
    protected void onNewIntent(final Intent intent) {
     ...
      if (intent.getScheme().equals(..)) {
        ..
      }
    }