2017-09-01 26 views
-2

所以我能夠顯示使用顯示按鈕的兩種不同顏色

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

的TextView與不同顏色的文字,但試圖做同樣的用

button.setText(...) 

當它不是文本工作!你知道按鈕文字中是否有不同的顏色?如果沒有,是否有其他解決方案?

編輯:我試過兩種解決方案建議,但沒有一個工作。我創建了一個新項目,只是要確定:

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(抱歉,我不能顯示圖像,由於低信譽)

我使用AS 2.3.3的Windows 10。模擬器使用帶有API 25的Android 7。感謝您的幫助!

+0

您可以在此線性佈局上使用簡單的線性佈局(水平)和文本視圖作爲按鈕和setOnClickListener。 –

+0

檢查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

試試這個:

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

如果你有android:textAllCaps = true你的按鈕它可能不是工作。嘗試將其設置爲false