Android 更改后如何更改EditText的颜色?
如果文本包含“(”和“),我希望更改android EditText的颜色。括号有特殊含义,字符串需要更改颜色。请任何人帮助。Android 更改后如何更改EditText的颜色?,android,colors,Android,Colors,如果文本包含“(”和“),我希望更改android EditText的颜色。括号有特殊含义,字符串需要更改颜色。请任何人帮助。EditText扩展TextView,它有一个名为setTextColor(int-color)的方法 您可以这样做: text.addTextChangedListener(new TextWatcher(){ public void afterTextChanged(Editable s) { if(s.toString().contains(
EditText
扩展TextView
,它有一个名为setTextColor(int-color)的方法
您可以这样做:
text.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if(s.toString().contains("(") && s.toString().contains(")")){
EditText text = (EditText) findViewById(R.id.id_of_text);
text.setTextColor(color);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
请注意,您不希望每次文本更改时都调用findviewbyd()
,因为它非常慢,所以请全局存储该引用
编辑:请注意setTextColor()
中的参数color
是一种颜色,而不是资源。因此,要从资源中获取颜色,您需要使用以下选项:
getResources().getColor(R.color.color_id);
用于编辑文本
范例
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.isEmpty(s)) {
String text = s.toString();
if(text.contains("(") || text.contains(")")) {
editText.setTextColor(Color.RED);
} else {
editText.setTextColor(Color.BLACK);
}
}
}
});
你看过
TextWatcher
了吗
您可以在每次更改后检查输入的字符串,并按照您认为合适的格式设置它。您的意思是更改字母的颜色吗?请按照以下问题进行操作。似乎在做同样的事情。可能重复的谢谢。。。精确而完美的答案。。。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.isEmpty(s)) {
String text = s.toString();
if(text.contains("(") || text.contains(")")) {
editText.setTextColor(Color.RED);
} else {
editText.setTextColor(Color.BLACK);
}
}
}
});