使用 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()
中提取代码并更改 yourEditText
到 this
,或者将其放在构造函数中:
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/