Android Linkify Phone 数字 - 如何指定哪些数字 link 哪些不

Android Linkify Phone Numbers - how to specify which numbers to link and which not to

我正在 Java 中编写一个 Android 应用程序,它显示与西班牙相关的信息,包括 phone 号码。

我正在使用 Linkify 使这些 phone 数字在使用此代码显示时可链接

Linkify.addLinks(textViewPlaceNotesDetailView, Linkify.PHONE_NUMBERS);

这很好用。

我的问题是其他数字也显示为链接,即。像 1965 年这样的年份。

我该如何防止这种情况发生?我只希望 phone 个数字成为链接。

注意。我想指定数字的最小长度,在本例中为 9(西班牙语 phone 数字在格式 'xxx xxx xxx' 中为 9 位)。但是我还没弄清楚该怎么做。

您可以使用自定义 regex 链接 phone 号码。

 tv.setLinksClickable(true);
 //only find phone number
 //Pattern phoneNumberPattern = Pattern.compile("\d{3}\s\d{3}\s\d{3}");
 //find phone number or web url
 Pattern phoneNumberPattern = Pattern.compile("(\d{3}\s\d{3}\s\d{3})|((https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|])");
 Linkify.addLinks(tv, phoneNumberPattern,"");

所提供的 regex 正在检测适用于您的案例的 xxx xxx xxx 数字格式和网址。

改用 LinkifyCompat 似乎解决了这个问题。

我现在使用的代码是:

LinkifyCompat.addLinks(textViewPlaceNotesDetailView, Linkify.PHONE_NUMBERS | Linkify.WEB_URLS);

这适用于(西班牙语)phone 号码和网址。

我很确定这在我第一次尝试时没有解决问题,但从那时起我已经更新为使用最新的依赖项并且它现在可以正常工作。

我不知道哪个库处理这个,但我的依赖项现在看起来像这样:

implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'org.osmdroid:osmdroid-android:6.1.7'
implementation 'org.osmdroid:osmdroid-shape:6.1.6'
implementation 'com.google.android.gms:play-services-location:18.0.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.navigation:navigation-fragment:2.3.4'
implementation 'androidx.navigation:navigation-ui:2.3.4'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation files('libs/commons-net-3.3.jar')
implementation 'com.android.support:design'