Live character count for EditText

后端 未结 14 2137
清歌不尽
清歌不尽 2020-11-29 17:07

I was wondering what the best way to do a live character count of an edit-text box is in Android. I was looking at this but I couldn\'t seem to make any sense of it.

<
14条回答
  •  执念已碎
    2020-11-29 17:43

        You can use TextWatcher class to see text has changed and how much number of character remains.Here i have set counter of 140 characters.
    
        EditText typeMessageToPost;
        TextView number_of_character;
    public void onCreate(Bundle savedBundleInstance) {
            super.onCreate(savedBundleInstance);
    setContentView(R.layout.post_activity);
    typeMessageToPost.addTextChangedListener(mTextEditorWatcher);
    }
    private final TextWatcher mTextEditorWatcher=new TextWatcher() {
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
    
            }
    
            @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
                number_of_character.setText(String.valueOf(140-s.length()));
            }
        };
    

提交回复
热议问题