Android - 在EditText中更改String的一部分的背景颜色(突出显示文本)

时间:2014-04-09 14:20:30

标签: android android-edittext textview

我正在创建一个应用,其中有EditTextToggleButton。我想借助这些来创建一个荧光笔机制。例如,当ToggleButton的状态为 ON 时,将在EditText中输入的文本将具有绿色背景,就像它正在突出显示一样。同样,当ToggleButton状态更改为关闭时,EditText中的文字也会立即停止突出显示。

请帮助我。

先谢谢!!

3 个答案:

答案 0 :(得分:1)

您可以使用SpannableString更改部分文本的背景颜色,如下所述:Set color of TextView span in Android

另一种做同样事情的方法是从HTML加载文本,并将标记设置为您想要的背景颜色。

答案 1 :(得分:0)

要更改文字的颜色,请使用

textElement.setTextColor(0xFF00FF00); //this is green colour

要更改编辑文字的颜色,请使用

textElement.setBackgroundColor(Color.MAGENTA);

有关详情,请查看此link

答案 2 :(得分:0)

只需在onCheckedChangeListener上设置ToggleButton即可更改EditText的背景。您的代码将是这样的:

toggleButtonHighLight.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton button, boolean isChecked) {
        if (checked) {
            //highlight the EditText by setting its background to green
            editText.setBackgroundResource(R.color.green);
        } else {
            //delete the highlight when the toggleButton is OFF
            editText.setBackgroundColor(android.R.color.white);
        }
    }
});