2017-09-01 10 views
-2

とボタンのテキストを表示するので、私は2つの異なる色

String redString= "<font color='#ee0000'>yay</font>"; 
String blackString = "<font color='#000000'>eureka</font>"; 
textView.setText(Html.fromHtml(redString + blackString)); 

を使用して、異なる色でのTextViewのテキストを表示することができるよしかし

button.setText(...) 

と正確に同じことをやろうとしているとき、それはありません作業!ボタンのテキストに異なる色を付けることができるかどうか知っていますか?そうでない場合は、代替ソリューションがありますか?

EDIT:両方のソリューションを試してみましたが、いずれも機能しませんでした。私は、Windows 10.上の2.3.3 AS使用してい

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //first solution 
    String redString= "<font color='#ee0000'>yay </font>"; 
    String blackString = "<font color='#000000'>eureka</font>"; 
    TextView test1 = (TextView) findViewById(R.id.textView); 
    Button test2 = (Button) findViewById(R.id.button2); 
    test1.setText(Html.fromHtml(redString + blackString)); 
    test2.setText(Html.fromHtml(redString + blackString)); 

    //second solution 
    Button b = (Button) findViewById(R.id.button); 
    SpannableString text = new SpannableString("Hello World"); 
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0); 
    text.setSpan(new ForegroundColorSpan(Color.BLUE), 5, text.length(), 0); 
    b.setText(text, TextView.BufferType.SPANNABLE); 
    } 
} 

And this is the result(申し訳ありませんが、私は、低い評判に画像を表示することはできません)

:私は念のために、新しいプロジェクトを作成しましたエミュレータはAPI 25でAndroid 7を使用しています。ありがとうございました!

+0

この線形レイアウトでは、ボタンとしてテキストビューを使用し、単純な線形レイアウト(水平)を使用できます。 –

+0

check SpannableString –

+0

可能な解決策はこちら[https://stackoverflow.com/questions/19500350/use-2-or-more-colors-for-a-button-text]です。 –

答えて

1

使用このコード

Button b = (Button) findViewById(R.id.button1); 
SpannableString text = new SpannableString("Hello World"); 

text.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0); 

text.setSpan(new ForegroundColorSpan(Color.BLUE), 5, text.length(), 0); 

b.setText(text, BufferType.SPANNABLE); 
+1

が試行されましたが機能しませんでしたが、ボタンのテキストの色はまだデフォルトです!編集部分になります –

0

それは私の作品...

TextView test = (TextView) findViewById(R.id.ettx); 

     Button test2 = (Button) findViewById(R.id.ettxb); 

     String redString= "<font color='#ee0000'>yay</font>"; 
     String blackString = "<font color='#000000'>eureka</font>"; 
     test.setText(Html.fromHtml(redString + blackString)); 

     test2.setText(Html.fromHtml(redString + blackString)); 

enter image description here

0

この試してみてください:あなたはボタンのandroid:textAllCaps = trueをお持ちの場合は

TextView b = (TextView) findViewById(R.id.text); 

SpannableString text = new SpannableString("Color Change"); 

text.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 0); 

text.setSpan(new ForegroundColorSpan(Color.GREEN), 5, text.length(), 0); 

b.setText(text, TextView.BufferType.SPANNABLE); 
0

をないかもしれない仕事。 falseに設定してみてください。

関連する問題