Android editText 輸入字數限制 – Android移動開發技術文章_手機開發 Android移動開發教學課程

方法一:


view plaincopy to clipboardprint?
// 輸入框限制輸入字數  
        editText.addTextChangedListener(new TextWatcher() {  
            private CharSequence temp;  
            private boolean isEdit = true;  
            private int selectionStart ;  
            private int selectionEnd ;  
            @Override 
            public void beforeTextChanged(CharSequence s, int arg1, int arg2,  
                    int arg3) {  
                temp = s;  
            }  
   
            @Override 
            public void onTextChanged(CharSequence s, int arg1, int arg2,  
                    int arg3) {  
            }  
   
            @Override 
            public void afterTextChanged(Editable s) {  
                 selectionStart = editText.getSelectionStart();  
                selectionEnd = editText.getSelectionEnd();  
                Log.i(“gongbiao1”,””+selectionStart);  
                if (temp.length() > Constant.TEXT_MAX) {  
                    Toast.makeText(KaguHomeActivity.this,  
                            R.string.edit_content_limit, Toast.LENGTH_SHORT)  
                            .show();  
                    s.delete(selectionStart-1, selectionEnd);  
                    int tempSelection = selectionStart;  
                    editText.setText(s);  
                    editText.setSelection(tempSelection);  
                }  
            }  
   
   
        }); 
// 輸入框限制輸入字數
        editText.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private boolean isEdit = true;
            private int selectionStart ;
            private int selectionEnd ;
            @Override
            public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                    int arg3) {
                temp = s;
            }
 
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                    int arg3) {
            }
 
            @Override
            public void afterTextChanged(Editable s) {
                 selectionStart = editText.getSelectionStart();
                selectionEnd = editText.getSelectionEnd();
                Log.i(“gongbiao1”,””+selectionStart);
                if (temp.length() > Constant.TEXT_MAX) {
                    Toast.makeText(KaguHomeActivity.this,
                            R.string.edit_content_limit, Toast.LENGTH_SHORT)
                            .show();
                    s.delete(selectionStart-1, selectionEnd);
                    int tempSelection = selectionStart;
                    editText.setText(s);
                    editText.setSelection(tempSelection);
                }
            }
 
 
        });


方法二:
利用EditText 可以設置filter的特性,自定義一個LengthFilter,當輸入字數超過限制時 ,做出自定義的提示


view plaincopy to clipboardprint?
// 輸入框限制輸入字數  
       InputFilter[] filters = new InputFilter[1]; 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。