Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 EditTextWithDel:帶一鍵清除功能的輸入框

編輯:關於 Android 程式設計

做了一個很實用的小控制項 EditTextWithDel:在系統輸入框右側加一個小圖示,點一下就清空已輸入的內容。Android 原生的 EditText 沒有這個能力,所以必須自己擴充。

效果如下:

實作思路

核心有兩部分:用 setCompoundDrawablesWithIntrinsicBounds 在右側掛上刪除圖示,再依內容有無決定要不要顯示它;點擊判斷則是靠記住手指按下的座標,在 onTouchEvent 中模擬出「點了右側圖示」這個事件——因為直接給 EditText 的 compound drawable 掛 OnClickListener 是行不通的。

package com.xiaolijuan.edittextwithdeldome;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;

/**
 * 自定義帶有刪除功能的 EditText
 */
public class EditTextWithDel extends EditText {

    private final static String TAG = "EditTextWithDel";

    private Drawable imgInable;
    private Drawable imgAble;
    private Context mContext;

    public EditTextWithDel(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    public EditTextWithDel(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    private void init() {
        imgAble = mContext.getResources().getDrawable(R.mipmap.icon_delete_gray);

        // 內容改變時同步切換右側圖示
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void afterTextChanged(Editable s) {
                setDrawable();
            }
        });
        setDrawable();
    }

    /** 設定右側刪除圖示:無內容時隱藏 */
    private void setDrawable() {
        if (length() < 1) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, imgAble, null);
        }
    }

    /** 處理刪除事件 */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) {
            int eventX = (int) event.getRawX();
            int eventY = (int) event.getRawY();
            Log.e(TAG, "eventX = " + eventX + "; eventY = " + eventY);

            Rect rect = new Rect();
            getGlobalVisibleRect(rect);   // 取控制項在螢幕上的可見範圍
            rect.left = rect.right - 50;  // 只保留最右側 50 像素作為觸發區

            if (rect.contains(eventX, eventY)) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }
}

setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom) 一次就能在上、下、左、右四個方位掛圖示,不需要顯示的位置傳 null 即可。這裡只在第三個參數(右側)放刪除圖示。

onTouchEvent 中的判斷有兩個關鍵:一是必須用 getRawX/getRawY 取得螢幕絕對座標,而不是 event.getX() 這種相對座標,才能和 getGlobalVisibleRect 得到的範圍對齊;二是把範圍的 left 改成 right - 50,等於把觸發區縮到最右側一小塊,避免點到輸入框其他地方也被判定為點擊刪除。

佈局檔

一個自定義輸入框加上一個按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="25dp"
        android:background="#ffffff">

        <ImageView
            android:id="@+id/img"
            android:layout_width="25dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_margin="5dp"
            android:src="@mipmap/ic_launcher" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:background="#56AB55" />

        <com.xiaolijuan.edittextwithdeldome.EditTextWithDel
            android:id="@+id/et_phoneNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_margin="2dp"
            android:layout_toRightOf="@+id/img"
            android:background="#ffffff"
            android:hint="請輸入手機號碼"
            android:maxLength="11"
            android:phoneNumber="true"
            android:singleLine="true" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="25dp"
        android:background="#56AB55"
        android:text="確定" />
</LinearLayout>

Activity 程式碼

package com.xiaolijuan.edittextwithdeldome;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userName = (EditText) findViewById(R.id.et_phoneNumber);

        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(userName.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "手機號碼為空", Toast.LENGTH_LONG).show();
                    return;
                }
                Toast.makeText(getApplicationContext(), userName.getText().toString(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

原始碼下載:https://xiazai.jb51.net/201609/yuanma/EditTextWithDel(jb51.net).rar

這個控制項的價值在於它把「何時顯示清除鈕」與「點擊清除區的判定」都收進自己內部,外部使用時完全不需要多寫任何程式碼,就跟用原生 EditText 一樣。若要進一步打磨,可以加上圖示淡入淡出的過場,或改成在獲得焦點且已有內容時才顯示,讓互動更貼近主流 App 的習慣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved