答案 0 :(得分:2)
您可以使用spannable绘制EditText文本的不同部分:
final SpannableStringBuilder sb = new SpannableStringBuilder(charSequence.toString());
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 0, 0));
//final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // You can make the text bold!
sb.setSpan(fcs, yourTextLimit, charSequence.toString().length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
参考:This answer
将onChanged侦听器设置为EditText,当文本大小超出限制时,可以使用上面的代码更改文本颜色
public class MainActivity extends AppCompatActivity {
EditText test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = (EditText) findViewById(R.id.test);
test.addTextChangedListener(new TextWatcher() {
boolean changed = true;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int yourTextLimit = 10;
final SpannableStringBuilder sb = new SpannableStringBuilder(charSequence.toString());
if (charSequence.toString().length() > yourTextLimit && changed) {
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 0, 0));
//final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // You can make the text bold!
// sb.setSpan(bss, yourTextLimit, charSequence.toString().length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(fcs, yourTextLimit, charSequence.toString().length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(new MyClickableSpan(charSequence.toString()), 0, charSequence.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
changed = false;
test.setText(sb);
} else if (changed) {
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(0, 0, 0));
sb.setSpan(fcs, 0, charSequence.toString().length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(new MyClickableSpan(charSequence.toString()), 0, charSequence.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
changed = false;
test.setText(sb);
}
test.setSelection(charSequence.toString().length());
}
@Override
public void afterTextChanged(Editable editable) {
changed = true;
}
});
}
class MyClickableSpan extends ClickableSpan {// extend ClickableSpan
String clicked;
public MyClickableSpan(String string) {
super();
clicked = string;
}
public void onClick(View tv) {
Toast.makeText(MainActivity.this,clicked , Toast.LENGTH_SHORT).show();
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
}
}