How to limit specific character in edit text?

烂漫一生 提交于 2020-04-16 05:47:50

问题


My question is that How to limit specific character in edit text?

for example I want to limit # character using max. 3 times in edit text.

How can I do this? Any advice or code sample please.

thanks.


回答1:


use this

yourEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if(count>3){
        yourEditText.setEnabled(false);

                  }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });



回答2:


Try this

int currHash=0;
    edtText.addTextChangedListener(new TextWatcher() {

        CharSequence previous;
        public void afterTextChanged(Editable source) {
        if(source.toString().contains("#") && currHash=2){
              source.clear();
              source.append(previous.toString());
        }
        else 
             if(source.toString().contains("#"))
                currHash++;
      }

      public void beforeTextChanged(CharSequence source, int start, int count, int after) {    
            previous = source;
      }

      public void onTextChanged(CharSequence source, int start, int before, int count) {}
     });




回答3:


I found a solution like this.

etDesc.addTextChangedListener(new TextWatcher() {
             @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                 hastagCount = s.toString().length() - s.toString().replace("#", "").length();
                 if(hastagCount<=3){
                     previousDesc = s.toString();
                 }
             }

             @Override
             public void onTextChanged(CharSequence s, int start, int before, int count) {

             }

             @Override
             public void afterTextChanged(Editable s) {
                 hastagCount = s.toString().length() - s.toString().replace("#", "").length();
                 if(hastagCount>3){
                     s.clear();
                     s.append(previousDesc);
                     int pos = etDesc.getText().length();
                     etDesc.setSelection(pos);
                     etDesc.setFocusable(true);
                 }

             }
         });


来源:https://stackoverflow.com/questions/61031014/how-to-limit-specific-character-in-edit-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!