对按钮文本使用2种(或更多种)颜色

ton*_*099 2 android colors android-button android-view

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

button.setTextColor(getApplication().getResources().getColor(R.color.red)); //TAKE DEFAULT COLOR
Run Code Online (Sandbox Code Playgroud)

要么

button.setTextColor(0xff0000); //SET CUSTOM COLOR 
Run Code Online (Sandbox Code Playgroud)

要么

button.setTextColor(Color.parseColor("#ff0000")); 
Run Code Online (Sandbox Code Playgroud)

但是我想为文本使用两种颜色:例如,假设我的按钮具有以下文本:"Click Here",我希望"Click"部分显示为红色,"Here"部分显示为蓝色.

这可能吗 ?

Ami*_*pta 10

你应该使用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);
Run Code Online (Sandbox Code Playgroud)

OutPut:

在此输入图像描述

希望这会帮助你.