1. 程式人生 > >EditText限制輸入的字元數並彈出Toast提示字數已達上限

EditText限制輸入的字元數並彈出Toast提示字數已達上限

大家對EditText這個控制元件並不陌生,它是一個可供我們輸入文字內容的輸入框。前些日子需要實現這樣一個需求:限制EditText中可以輸入的最大字元數為6,達到6時,使用者每按一次軟鍵盤就彈出一個Toast提示使用者,並且無法再輸入內容。就像下圖的效果:

這裡寫圖片描述

一開始我是直接在佈局檔案中在使用android:maxLength的屬性將文字長度寫死,然後再到程式碼中去監聽,但是這樣一來,監聽也就失去了意義了,因為無論使用者怎麼輸入,EditText中容納的文字長度最長都是6,超過6時就不起作用了。所以我最終拋棄了這個寫法,不再把文字長度寫死了。現在就讓我們看看具體怎麼實現吧。

新建一個工程,在MainActivity的佈局裡放置一個EditText:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom
="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.lindroid.edittextchangedemo.MainActivity">
<EditText android:id
="@+id/edit" android:hint="請在此輸入內容" android:layout_width="match_parent" android:layout_height="wrap_content" />
</RelativeLayout>

然後到程式碼中實現EditText中的輸入監聽事件,即介面TextWatcher中的方法。由於我們需要監聽的是文字長度的變化,也就是文字輸入過程中的變化,所以複寫onTextChanged方法即可:

public class MainActivity extends AppCompatActivity {
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.edit);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 6){ //判斷EditText中輸入的字元數是不是已經大於6
                    editText.setText(s.toString().substring(0,6)); //設定EditText只顯示前面6位字元
                    editText.setSelection(6);//讓游標移至末端
                    Toast.makeText(MainActivity.this, "輸入字數已達上限", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}

程式碼只有寥寥幾行,首先我們需要判斷使用者輸入的字串長度是否已經超過了6(引數CharSequence 即EditText中輸入的字串),如果超過了6,我們就只顯示前面6位字元,並彈出一條Toast告訴使用者 “輸入字數已達上限”,不能再輸入了。同時,為了使用者操作方便,比如可以刪除剛剛輸入的內容,我們將游標設定在文字的末端。

好了,整個Demo就這麼簡單,其實我們就是把使用者輸入的內容先攔截下來,篩選之後再顯示到EditText上而已。

相關推薦

no