显示具有两种不同颜色的按钮文本

时间:2017-09-01 10:20:27

标签: java android button text colors

所以我可以使用

显示不同颜色的textView文本
String redString= "<font color='#ee0000'>yay</font>";
String blackString = "<font color='#000000'>eureka</font>";
textView.setText(Html.fromHtml(redString + blackString));

但尝试与

完全相同时
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(抱歉,由于声誉不佳,我无法显示图片)

我在Windows 10上使用AS 2.3.3。模拟器使用带有API 25的Android 7.感谢您的帮助!

4 个答案:

答案 0 :(得分: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 :(得分:1)

对我有用......

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

答案 2 :(得分:1)

如果您的按钮有android:textAllCaps = true,则可能无效。尝试将其设置为false

答案 3 :(得分: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);