簡體   English   中英

Android Linkify 電話號碼 - 如何指定要鏈接的號碼和不鏈接的號碼

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

我正在用 Java 編寫一個 Android 應用程序,它顯示與西班牙有關的信息,包括電話號碼。

我正在使用 Linkify 使這些電話號碼在使用此代碼顯示時可鏈接

Linkify.addLinks(textViewPlaceNotesDetailView, Linkify.PHONE_NUMBERS);

這工作正常。

我的問題是其他數字也顯示為鏈接,即。 像 1965 年這樣的年份。

我怎樣才能防止這種情況? 我只希望電話號碼是鏈接。

注意。 我想為號碼指定一個最小長度,在這種情況下是 9(西班牙電話號碼是 9 位數字,格式為“xxx xxx xxx”)。 但我一直無法弄清楚如何做到這一點。

那么您可以使用自定義regex來鏈接電話號碼。

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

這適用於(西班牙語)電話號碼和 URL。

我很確定這在我第一次嘗試時並沒有解決問題,但從那時起我已經更新為使用最新的依賴項,現在可以正常工作了。

我不知道哪個庫處理這個問題,但我的依賴項現在看起來像這樣:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM