Android:TextView.setText()を使用して文字列の一部に色を付けますか?


86

.setText( "")メソッドを使用してTextViewビューのテキストを変更すると同時に、テキストの一部を色付け(または太字、斜体、透明など)、残りの部分は変更しないようにしています。例えば:

title.setText("Your big island <b>ADVENTURE!</b>";

上記のコードが正しくないことは知っていますが、それは私が達成したいことを説明するのに役立ちます。どうすればよいですか?



TextViewに長いテキストがある場合は、より効率的な方法
Mingfei 2015


スパン使用してKotlinにおけるソリューションstackoverflow.com/a/59510004/11166067
Dmitriiレオーノフを

回答:


201

スパンを使用します

例:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb);

11
私の言葉の文字数がわからないため、多言語では機能しないため、Androidがここで提供するソリューションは本当に好きではありません。私は現在、すべてをTextViewにアタッチして、それらをまとめることができる複数のスパンを持つことができるソリューションを探しています
philipp

1
テキストを太字にするスパンと言うコメント、テキストの色を作るスパンと言うべきですか?
ライハン2013

9
@philipp問題が単語の文字数である場合は、StringまたはStringBuilderなどでlength()メソッドを使用します
Ahmed Adel Ismail

1
TextViewに長いテキストがある場合は、より効率的な方法があります
Mingfei 2015

答えを読んだときに最初はこれを見逃しましたが、終了インデックスは文字列の終了インデックス+1である必要があります(つまり、最初の4文字にまたがるには、[start、end]を[0、4]ではなく[0、4]に設定する必要があります。 3])
tir38 2016年

46
title.setText(Html.fromHtml("Your big island <b>ADVENTURE!</b>")); 

2
これは、マークされた答えよりも、元の問題に対するはるかに優れた解決策です。
bSnapZ 2014

1
改行がある場合\ n、改行は表示されません。
ライブラブ

8
いいえ、それは良くありません、問題に言及されている着色機能はありませんが、HTML()からのSLOWメソッド
Viktor Yakunin

1
それで、使用<font color="#FFAADD>text</font>は機能しませんか?
milosmns 2017年

25

これがお役に立てば幸いです(多言語で動作します)。

<string name="test_string" ><![CDATA[<font color="%1$s"><b>Test/b></font>]]> String</string>

そして、Javaコードでは、次のことができます。

int color = context.getResources().getColor(android.R.color.holo_blue_light);
String string = context.getString(R.string.test_string, color);
textView.setText(Html.fromHtml(string));

このように、「テスト」部分のみが色付け(および太字)されます。


3
ベストアンサー。これは、国際化された文字列に対して完全に機能します。また、文字列リソースの中央に色付きのテキストを配置できるという利点もあります。
jt-gilkeson 2015

詳細については、こちらの「HTMLマークアップを使用したスタイリング」セクションを参照してください
エリザベス

17

単語のすべての出現箇所(大文字と小文字を区別しない)を検索し、それらを赤に色付けする例を次に示します。

String notes = "aaa AAA xAaax abc aaA xxx";
SpannableStringBuilder sb = new SpannableStringBuilder(notes);
Pattern p = Pattern.compile("aaa", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(notes);
while (m.find()){
    //String word = m.group();
    //String word1 = notes.substring(m.start(), m.end());

    sb.setSpan(new ForegroundColorSpan(Color.rgb(255, 0, 0)), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
editText.setText(sb);

私はあなたの名前が大好きです:P新しいBackgroundColorSpan(Color.parseColor( "#BFFFC6"))で特定の単語の背景を変更できますか?
Ajay Pandya 2017

8

を使用しSpannableて、テキストの特定の部分に特定の側面を与えることができます。必要に応じて例を調べることができます。

ああ、ここからstackoverflowで

TextView TV = (TextView)findViewById(R.id.mytextview01); 
Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(WordtoSpan);

多言語テキストの開始範囲と終了範囲をどのように構成できますか?
ムバラク

8

Kotlinを使用している場合は、android-ktxライブラリを使用して次の操作を実行できます

val title = SpannableStringBuilder()
        .append("Your big island ")
        .bold { append("ADVENTURE") } 

titleTextField.text = title

bold上の拡張機能ですSpannableStringBuilder。使用できる操作のリストについては、こちらのドキュメントを参照してください。

もう一つの例:

val ssb = SpannableStringBuilder()
            .color(green) { append("Green text ") }
            .append("Normal text ")
            .scale(0.5F) { append("Text at half size ") }
            .backgroundColor(green) { append("Background green") }

green解決されたRGBカラーはどこにありますか。

スパンをネストすることも可能であるため、埋め込みDSLのようなものになります。

bold { underline { italic { append("Bold and underlined") } } }

それが機能するためには、アプリモジュールレベルbuild.gradleで以下が必要になります。

repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:0.3'
}

また、どの色を入れても同じ紫色になります。 val spannableStringBuilder = SpannableStringBuilder() spannableStringBuilder.bold { underline { color(R.color.test_color) { append(underlinedText) } } }
アビシェークサクセナ

4

HTMLを使用する場合は、 TextView.setText(Html.fromHtml(String htmlString))

それを頻繁に/繰り返し行いたい場合は、私が書いたクラス(SpannableBuilder)を見てください。Html.fromHtml()あまり効率的ではありません(内部で大きなxml解析機構を使用しています)。このブログ投稿で説明されています。


4
public static void setColorForPath(Spannable spannable, String[] paths, int color) {
    for (int i = 0; i < paths.length; i++) {
        int indexOfPath = spannable.toString().indexOf(paths[i]);
        if (indexOfPath == -1) {
            continue;
        }
        spannable.setSpan(new ForegroundColorSpan(color), indexOfPath,
                indexOfPath + paths[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

使用する

Spannable spannable = new SpannableString("Your big island ADVENTURE");
Utils.setColorForPath(spannable, new String[] { "big", "ADVENTURE" }, Color.BLUE);

textView.setText(spannable);

ここに画像の説明を入力してください


3

            String str1 = "If I forget my promise to ";
            String penalty = "Eat breakfast every morning,";
            String str2 = " then I ";
            String promise = "lose my favorite toy";
           

            String strb = "<u><b><font color='#081137'>"+ penalty +",</font></b></u>";
            String strc = "<u><b><font color='#081137'>"+ promise + "</font></b></u>";
            String strd = str1 +strb+ str2 + strc;
           tv_notification.setText(Html.fromHtml(strd));

またはこのコードを使用します:

    SpannableStringBuilder builder = new SpannableStringBuilder();
            SpannableString text1 = new SpannableString(str1);
            text1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)), 0, str1.length() - 1, 0);
            builder.append(text1);

            SpannableString text2 = new SpannableString(penalty);
            text2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, penalty.length(), 0);
            text2.setSpan(new UnderlineSpan(), 0, penalty.length(), 0);
            builder.append(text2);

            SpannableString text3 = new SpannableString(str2);
            text3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)),0, str2.length(), 0);
            builder.append(text3);


            SpannableString text4 = new SpannableString(promise);
            text4.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, promise.length(), 0);
            text4.setSpan(new UnderlineSpan(),0, promise.length(), 0);
            builder.append(text4);

          tv_notification.setText(builder);


3

SpannableStringBuilder文字列の長さを計算してsetSpanを呼び出すのではなく、さまざまなスパンを1つずつ追加して使用するのが好きです。

として:(Kotlinコード)

val amountSpannableString = SpannableString("₹$amount").apply {
  // text color
  setSpan(ForegroundColorSpan("#FD0025".parseColor()), 0, length, 0)
  // text size
  setSpan(AbsoluteSizeSpan(AMOUNT_SIZE_IN_SP.spToPx(context)), 0, length, 0)
  // font medium
  setSpan(TypefaceSpan(context.getString(R.string.font_roboto_medium)), 0, length, 0)
}

val spannable: Spannable = SpannableStringBuilder().apply {
  // append the different spans one by one
  // rather than calling setSpan by calculating the string lengths
  append(TEXT_BEFORE_AMOUNT)
  append(amountSpannableString)
  append(TEXT_AFTER_AMOUNT)
}

結果


2

2つ以上のスパンを連結できます。この方法では、長さの値を使用して動的テキストに色を付けるのが簡単です。

SpannableStringBuilder span1 = new SpannableStringBuilder("Android");
ForegroundColorSpan color1=new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
span1.setSpan(color1, 0, span1.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

SpannableStringBuilder span2 = new SpannableStringBuilder("Love");
ForegroundColorSpan color2=new ForegroundColorSpan(getResources().getColor(R.color.colorSecondary));
span2.setSpan(color2, 0, span2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

Spanned concatenated=(Spanned) TextUtils.concat(span1," => ",span2);

SpannableStringBuilder result = new SpannableStringBuilder(concatenated);

TextView tv = (TextView) rootView.findViewById(R.id.my_texview);
tv.setText(result, TextView.BufferType.SPANNABLE);

2

このコードを使用すると便利です

TextView txtTest = (TextView) findViewById(R.id.txtTest);
txtTest.setText(Html.fromHtml("This is <font color="#ff4343">Red</font> Color!"));

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.