Android 上 TextView 中的多个可点击链接

2022-01-09 00:00:00 android android-layout java textview

我正在尝试在类似于 Google & 的文本视图中添加多个链接.Flipboard 的条款和条件和隐私政策如下面的屏幕截图所示:

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());

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

myHtml 是一个 href.

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?

推荐答案

你可以使用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:");

然后您可以使用该方案来启动一个活动,例如通过在 AndroidManifest 中添加该方案:

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>

如果您想执行自定义操作,可以将 Intent-filter 设置为您当前的活动,这将有一个 singleTop 启动模式.

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

这将导致 onNewIntent 在哪里被触发可以进行自定义操作:

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

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

相关文章