我正在 EditText
中写一些文本,当我写 "#data" 时,它的颜色应该改变,但不会改变我该怎么做。请检查下面我用过的EditText
<EditText
android:id="@+id/et_simple"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</EditText>
最佳答案
希望这个解决方案会有所帮助..!
我用过这个解决方案,它非常有用!比如在 editText 上添加 textWatcher 接口(interface)并监听 textChange 并找出单词是否以 hashTag 开头,然后调用该单词的 Change The color 方法!它有一些缺陷,但可以忽略不计,请在此处查看这个简单的缺陷。
Spannable mspanable;
int hashTagIsComing = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edtTxtMine = (EditText) findViewById(R.id.editText1);
mspanable = edtTxtMine.getText();
edtTxtMine.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String startChar = null;
try{
startChar = Character.toString(s.charAt(start));
Log.i(getClass().getSimpleName(), "CHARACTER OF NEW WORD: " + startChar);
}
catch(Exception ex){
startChar = "";
}
if (startChar.equals("#")) {
changeTheColor(s.toString().substring(start), start, start + count);
hashTagIsComing++;
}
if(startChar.equals(" ")){
hashTagIsComing = 0;
}
if(hashTagIsComing != 0) {
changeTheColor(s.toString().substring(start), start, start + count);
hashTagIsComing++;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
private void changeTheColor(String s, int start, int end) {
mspanable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
关于android - 如何在 EditText 中以不同颜色标记值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51500782/