帶刪除按鈕的EditText

在使用輸入框的時候,常常需要在輸入框後帶有一鍵清除輸入內容的按鈕。採用自定義View的方式是複用性較高的方法。另一方面也可以採用控件“控件+監聽”的較爲簡單的方法來實現。

佈局文件:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="賬號:"
        android:textColor="#000000"
        android:gravity="center"
        android:textSize="16sp"/>
    <EditText
        android:id="@+id/etUser"
        tools:text="test3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="@null"
        android:maxLength="16"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/closeUser"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:gravity="center"
        android:background="@drawable/icon_delete"
        android:textColor="@color/gray"/>
</LinearLayout>

主要代碼:

        tvCloseUser = (TextView) findViewById(R.id.closeUser);//清除按鈕,使用TextView
        tvCloseUser.setVisibility(View.INVISIBLE);
        
        mEtUserName = (EditText) findViewById(R.id.etUser);//文本框
        
        //監聽文本變化
        mEtUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0){
                    tvCloseUser.setVisibility(View.VISIBLE);
                }else{
                    tvCloseUser.setVisibility(View.GONE);
                }
            }
        });
        //點擊清除文本
        tvCloseUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtUserName.setText("");
            }
        });
        //監聽焦點變化,沒有焦點則清除按鈕不可見
        mEtUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && mEtUserName.getText().length() > 0){
                    tvCloseUser.setVisibility(View.VISIBLE);
                }else {
                    tvCloseUser.setVisibility(View.GONE);
                }
            }
        });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章