0

オブジェクトでtoStringを呼び出すコードの一部があり、toStringは基本的に画面に表示される文字列を吐き出します。

紐の一部の色を変えたいです。

私はちょうどこのようなことを試しました:

        String coloredString =  solutionTopicName + " (" + commentCount +  ")";
        Spannable sb = new SpannableString( coloredString );
        ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
        sb.setSpan(new ForegroundColorSpan(Color.BLUE), solutionTopicName.length(), solutionTopicName.length()+3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return sb.toString();   

しかし、私はまだ同じ色が変わらずに表示されているのを見ています.

ありがとう!

4

2 に答える 2

2

はい、可能です

そのためにSpannableを使用します。

setSpan()仕事をします。

Spannable mString = new SpannableString("multi color string ");        

mString.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

アップデート:

String coloredString = " (" + solutionTopicName + commentCount +  ")";
        Spannable sb = new SpannableString( coloredString );
        ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
        sb.setSpan(new ForegroundColorSpan(Color.BLUE), solutionTopicName.length(), solutionTopicName.length()+3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //textView.setText(sb);
    return sb;

最新:

 String solutionTopicName= "Hello";
 String commentCount= "hi how are you";
 String coloredString =  solutionTopicName+"(" + commentCount +  ")";
 Spannable sb = new SpannableString( coloredString );
 sb.setSpan(new ForegroundColorSpan(Color.BLUE), coloredString.indexOf("("), coloredString.indexOf(")")+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  mTextView.setText(sb);
于 2012-05-19T05:44:18.850 に答える
1
I would like to change the color of one part of the string. Is that at all possible?

はい、文字列の特定の部分の色を変更できます。SpannableStringBuilder活用できるクラスが あります。

このようなことができます。

SpannableStringBuilder sb = new SpannableStringBuilder("This is your String");
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
sb.setSpan(fcs, 0, 10, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);  

ここに setspan メソッドの定義があります。

setSpan(Object what, int start, int end, int flags)
Mark the specified range of text with the specified object.  

setSpanメソッドは、パラメータとしてインデックスとObjectClass のインスタンスを取ります。そのため、要件に応じて、任意のクラスのインスタンスをパラメーターとして渡すことができます。のインスタンスを使用ForegroundColorSpanして、テキストの色を変更しました。インスタンスを渡しClickableて、文字列の特定の部分をクリック可能にすることができます。

于 2012-05-19T05:46:45.933 に答える