Use 2 (or more) colors for a button text

*爱你&永不变心* 提交于 2019-12-11 00:01:32

问题


I know I can change the color of the text on a button by the following ways :

button.setTextColor(getApplication().getResources().getColor(R.color.red)); //TAKE DEFAULT COLOR

or

button.setTextColor(0xff0000); //SET CUSTOM COLOR 

or

button.setTextColor(Color.parseColor("#ff0000")); 

However I want to use two colors for the text : for example, suppose my button has the following text : "Click Here" , I want the "Click" part to appear in red, and the "Here" part in blue.

Is this possible ?


回答1:


You should use ForegroundColorSpan

Try like this,

        Button b = (Button) findViewById(R.id.button1);
        SpannableString text = new SpannableString("Click Here");
        // make "Clicks" (characters 0 to 5) Red
        text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);
        // make "Here" (characters 6 to 10) Blue
        text.setSpan(new ForegroundColorSpan(Color.BLUE), 6, 10, 0);
        // shove our styled text into the Button
        b.setText(text, BufferType.SPANNABLE);

OutPut:

Hope this will help you.




回答2:


Yes it is possible

do like this

        Button btn = (Button) findViewById(R.id.btn);

        btn.setText(Html.fromHtml("<font color='red'>Click</font>"
            + "<font color='blue'> Here</font>"));


来源:https://stackoverflow.com/questions/19500350/use-2-or-more-colors-for-a-button-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!