15

textview単語ごとに異なる色を使用することは可能ですか?それともすべての手紙?拡張textviewして作成してみましたが、問題は、すべてのテキストを異なる色で同時に描画するにはどうすればよいかということです。

4

3 に答える 3

32

使用するandroid.text.Spannable

final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
    new ForegroundColorSpan(Color.BLUE), 
    wordStart, 
    wordEnd, 
    SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);

編集:すべての「Java」を緑色にするには

final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);

final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
    spannable.setSpan(
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );
}
myTextView.setText(spannable);
于 2012-07-13T23:28:11.453 に答える
21

このクラスを使用すると、メソッドを介してSpannableStringCharacterStyleの拡張機能(つまり)を適用することにより、文字列の特定の部分(スパン)を一方向に、他の部分を別の方向に簡単にフォーマットできます。ForegroundColorSpansetSpan

あなたはこれを試すことができます:

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    richTextView = (TextView)findViewById(R.id.rich_text);

    // this is the text we'll be operating on
    SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");

    // make "Lorem" (characters 0 to 5) red
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);

    // make "ipsum" (characters 6 to 11) one and a half time bigger than the textbox
    text.setSpan(new RelativeSizeSpan(1.5f), 6, 11, 0);

    // make "dolor" (characters 12 to 17) display a toast message when touched
    final Context context = this;
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
        }
    };
    text.setSpan(clickableSpan, 12, 17, 0);

    // make "sit" (characters 18 to 21) struck through
    text.setSpan(new StrikethroughSpan(), 18, 21, 0);

    // make "amet" (characters 22 to 26) twice as big, green and a link to this site.
    // it's important to set the color after the URLSpan or the standard
    // link color will override it.
    text.setSpan(new RelativeSizeSpan(2f), 22, 26, 0);
    text.setSpan(new URLSpan("http://www.chrisumbel.com"), 22, 26, 0);
    text.setSpan(new ForegroundColorSpan(Color.GREEN), 22, 26, 0);

    // make our ClickableSpans and URLSpans work
    richTextView.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView        
    richTextView.setText(text, BufferType.SPANNABLE);
}

結果は次のようになります。

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

詳細については、ChrisUmbelブログを参照してください。

于 2012-07-13T23:38:44.940 に答える
4

はい、 SpannableSpannableStringBuilderを使用してこれを行うことができます。1つの例については、スパンテキストとスパン可能テキストに関する例はありますかを参照してください。

テキストをフォーマットするさまざまな方法(背景色、前景色、クリック可能など)については、CharacterStyleを参照してください。

于 2012-07-13T23:29:01.020 に答える