我正在用 Java 開發一個應用程式,其 targetSdkVersion 設定為 30。我有一個活動,我需要向用戶顯示一個可點擊的 URL,其形式為單擊我,其中長 URL 隱藏在支持的 HTML 中。
我掙扎了一段時間。目前我的代碼如下
if (station.getSponsorUrl().length() > 32) {
stationSponsorUrl.setClickable(true);
stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
stationSponsorUrl.setText(Html.fromHtml("<a href=\"" station.getSponsorUrl() "\">" getString(R.string.www_link) "</a>\n", HtmlCompat.FROM_HTML_MODE_LEGACY));
}
else {
stationSponsorUrl.setText(station.getSponsorUrl());
}
當我洗掉setMovementMethod對 URL的呼叫時,會正確呈現(字體顏色),但它根本不可點擊。當我保持setMovementMethod活動狀態時,它甚至不會顯示為 URL。我看到由R.string.www_link未更改的格式定義的文本。當然,它也不起作用。
else案例作業正常,當我使用純 HTML 鏈接設定電視內容時,它開箱即用。電視在 XML 布局中定義如下
<TextView
android:id="@ id/textViewSponsorUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:autoLink="all"
android:fontFamily="@font/alegreya_sans_sc_medium"
android:linksClickable="true"
android:text="TextView"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
uj5u.com熱心網友回復:
您android:autoLink="all"在布局中使用時遇到了麻煩。我建議您洗掉該自動鏈接行并按如下方式調整您的代碼:
stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
String anchorText;
if (station.getSponsorUrl().length() > 32) {
anchorText = getString(R.string.www_link)
} else {
anchorText = station.getSponsorUrl()
}
stationSponsorUrl.setMovementMethod(LinkMovementMethod.getInstance());
stationSponsorUrl.setText(
HtmlCompat.fromHtml(
"<a href=\"" station.getSponsorUrl() "\">" anchorText "</a>\n", HtmlCompat.FROM_HTML_MODE_LEGACY
)
);
您還可以使用setAutoLinkMask()關閉長 URL 的自動鏈接:
stationSponsorUrl.setAutoLinkMask(0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406436.html
標籤:
