其他分享
首页 > 其他分享> > android-如何在EditText中以不同颜色标记值?

android-如何在EditText中以不同颜色标记值?

作者:互联网

我在写“ #data”时在EditText中写一些文本,其颜色应更改,但不更改我该怎么办.请检查以下我使用过的EditText

<EditText
         android:id="@+id/et_simple"
         android:layout_height="wrap_content"
         android:layout_width="match_parent">
</EditText>

解决方法:

希望此解决方案将对您有所帮助.

我用这个解决方案非常有用!例如在您的editText上添加textWatcher界面,然后侦听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);
}

标签:hashtag,android-edittext,android
来源: https://codeday.me/bug/20191025/1925659.html