Linkifyを使用してリンクを作成した後、TextViewテキストを変更することはできますか?URLに名前とIDの2つのフィールドを設定したいのですが、テキストに名前を表示したいだけです。
そこで、名前とIDの両方を含むテキストを含むテキストビューから始め、linkifyして両方のフィールドに適切なリンクを作成します。しかし、表示のために、私はIDを表示したくありません。
これは可能ですか?
それはちょっと痛いですが、はい。したがって、Linkify は基本的にいくつかのことを行います。最初に、テキストビューの内容をスキャンして、URL の文字列と一致する文字列を探します。次に、一致するセクションの UrlSpan と ForegroundColorSpan を作成します。次に、TextView の MovementMethod を設定します。
ここで重要な部分は UrlSpan です。TextView を取得して getText() を呼び出すと、CharSequence が返されることに注意してください。それはおそらくある種のスパンドです。Spanned から、getSpans() と具体的には UrlSpans を求めることができます。これらのすべてのスパンがわかったら、リストをループして、古いスパン オブジェクトを見つけて、新しいスパン オブジェクトに置き換えることができます。
mTextView.setText(someString, TextView.BufferType.SPANNABLE);
if(Linkify.addLinks(mTextView, Linkify.ALL)) {
//You can use a SpannableStringBuilder here if you are going to
// manipulate the displayable text too. However if not this should be fine.
Spannable spannable = (Spannable) mTextView.getText();
// Now we go through all the urls that were setup and recreate them with
// with the custom data on the url.
URLSpan[] spans = spannable.getSpans(0, spannable.length, URLSpan.class);
for (URLSpan span : spans) {
// If you do manipulate the displayable text, like by removing the id
// from it or what not, be sure to keep track of the start and ends
// because they will obviously change.
// In which case you may have to update the ForegroundColorSpan's as well
// depending on the flags used
int start = spannable.getSpanStart(span);
int end = spannable.getSpanEnd(span);
int flags = spannable.getSpanFlags(span);
spannable.removeSpan(span);
// Create your new real url with the parameter you want on it.
URLSpan myUrlSpan = new URLSpan(Uri.parse(span.getUrl).addQueryParam("foo", "bar");
spannable.setSpan(myUrlSpan, start, end, flags);
}
mTextView.setText(spannable);
}
うまくいけば、それは理にかなっています。Linkify は、正しいスパンをセットアップするための優れたツールです。スパンは、テキストをレンダリングするときに解釈されます。