【问题标题】:Use 2 (or more) colors for a button text为按钮文本使用 2 种(或更多)颜色
【发布时间】:2013-10-21 16:52:40
【问题描述】:

我知道我可以通过以下方式更改按钮上文本的颜色:

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

或

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

或

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

但是我想为文本使用两种颜色:例如,假设我的按钮具有以下文本:“单击此处”,我希望“单击”部分显示为红色,而“此处”部分显示为蓝色.

这可能吗?

【问题讨论】:

    标签: android colors android-view android-button


    【解决方案1】:

    您应该使用 ForegroundColorSpan

    这样试试,

            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);
    

    输出:

    希望这会对你有所帮助。

    【讨论】:

    • 感谢您采取额外的步骤并打印出屏幕截图。高度赞赏。
    • 可扩展的东西是 java 还是 android 特定的?
    【解决方案2】:

    有可能

    这样做

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

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2018-12-22
      • 2020-11-06
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多