2017-09-01 82 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

相关问题