java - 根据文本更改 TextView 颜色

标签 java android textview ondraw

使用 onDraw,我想制作一个自定义 TextView ,根据其文本值改变颜色。例如,如果文本值是“你好”,我希望它是红色的,如果它说“再见”,我希望它是绿色的。任何帮助都将不胜感激。

最佳答案

我不太确定为什么要在 onDraw() 中执行此操作。除非您有充分的理由设置自定义 TextView/EditText,否则没有必要。

为了简化您的情况,您可以实现一个 TextWatcher 来执行此操作,并且在 onTextChanged() 中,您可以通过以下方式设置颜色使用 .equals() 比较字符串值。

以下是您的理论情况的示例:

final EditText yourEditText = /* findViewById maybe? */;
yourEditText.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.equalsIgnoreCase("hello"))
            yourEditText.setTextColor(Color.RED);
        else if (s.equalsIgnoreCase("bye"))
            yourEditText.setTextColor(Color.GREEN);
        else // if it says neither "hello" nor "bye"
            yourEditText.setTextColor(Color.BLACK);
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Nothing needs to happen here
    }

    public void afterTextChanged(Editable s) {
        // Nothing needs to happen here
    }
});

如果您觉得有必要在 onDraw() 中维护这一点,只需从 onTextChanged() 中提取代码并更改 yourEditTextthis,或者将其放在构造函数中:

public class YourTextView extends TextView { // Or extends EditText, doesn't matter
    public YourTextView(Context context) {
        this(context, null, 0);
    }

    public YourTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public YourTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        addTextChangedListener(new TextWatcher() {
            // Copy the TextWatcher code from the example above, replacing "yourEditText" with "YourTextView.this"
        });
    }

    // ... Rest of your class
}

关于java - 根据文本更改 TextView 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750146/

相关文章:

java - JUnit Jupiter (JUnit5) 中的参数化测试执行

java - 出现错误 : platform DatabasePlatform does not support NativeSequence

android - 在 Flutter 中从客户设备检索日志

android - 在 Android 上以编程方式打开屏幕

java - Android 编辑文本和对话框

java - 使用重写的抽象方法从父类(super class)访问私有(private)变量

java - 无法执行目标 maven-compiler-plugin 3.8.0 - org/codehaus/plexus/compiler/manager/NoSuchCompilerException

android - Facebook 只分享给一个 friend

android - 如何在 Android TextViews 中设置 BlockQuotes 的样式?

android - 如何滚动内容?