ユーザーが特定のキーワードを検索できる検索画面があり、そのキーワードが強調表示されるアプリケーションを開発しています。Html.fromHtml メソッドを見つけました。
しかし、それが適切な方法であるかどうかを知りたいです。
これについてあなたの見解を教えてください。
または、 s を手動で処理するよりもはるかに簡単Spannable
です。背景を強調表示する必要があるとは言わなかったので、テキストだけです。
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
xml リソースの色の値を使用:
int labelColor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!
Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE);
これは、スパン可能な文字列を使用して実現できます。以下をインポートする必要があります
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
次に、次のようなものを使用して、テキストの背景を変更できます。
TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
これにより、位置1〜4の文字が赤い色で強調表示されます。お役に立てれば!
代替ソリューション:代わりにWebViewを使用します。HTMLは操作が簡単です。
WebView webview = new WebView(this);
String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";
webview.loadData(summary, "text/html", "utf-8");
テキストの一部に下線と色を付けるには
あなたのstrings.xmlで
<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u></string>
その後の活動で
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
およびクリック可能なリンクの場合:
<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>
そしてあなたの活動で:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));
htmlエディターで作成した色とまったく同じ色が得られます。テキストビューを設定して、テキストビューの値と連結するだけです。Android はスパンの色をサポートしていません。エディタでフォントの色に変更すれば、準備完了です。
最初に文字列を HTML に変換してから、スパン可能に変換します。次のコードを提案するようにしてください。
Spannable spannable = new SpannableString(Html.fromHtml(labelText));
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);