Android---3種方式限制EditView輸入字數,androideditview

來源:互聯網
上載者:User

Android---3種方式限制EditView輸入字數(轉載),androideditview

 方法一:利用TextWatcher

Java代碼  
  1. editText.addTextChangedListener(new TextWatcher() {  
  2.            private CharSequence temp;  
  3.            private boolean isEdit = true;  
  4.            private int selectionStart ;  
  5.            private int selectionEnd ;  
  6.            @Override  
  7.            public void beforeTextChanged(CharSequence s, int arg1, int arg2,  
  8.                    int arg3) {  
  9.                temp = s;  
  10.            }  
  11.              
  12.            @Override  
  13.            public void onTextChanged(CharSequence s, int arg1, int arg2,  
  14.                    int arg3) {  
  15.            }  
  16.              
  17.            @Override  
  18.            public void afterTextChanged(Editable s) {  
  19.                 selectionStart = editText.getSelectionStart();  
  20.                selectionEnd = editText.getSelectionEnd();  
  21.                Log.i("gongbiao1",""+selectionStart);  
  22.                if (temp.length() > Constant.TEXT_MAX) {  
  23.                    Toast.makeText(KaguHomeActivity.this,  
  24.                            R.string.edit_content_limit, Toast.LENGTH_SHORT)  
  25.                            .show();  
  26.                    s.delete(selectionStart-1, selectionEnd);  
  27.                    int tempSelection = selectionStart;  
  28.                    editText.setText(s);  
  29.                    editText.setSelection(tempSelection);  
  30.                }  
  31.            }  
  32.   
  33.   
  34.        });  

 

方法二:利用InputFilter

    

Java代碼  
  1. editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});  //其中100最大輸入字數  

 

方法三:在XML中設定

Xml代碼  
  1. <EditText  
  2.     .  
  3.     .  
  4.     .  
  5.     android:maxLength="100"  
  6. />  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.