Android 帶清除功能的輸入框控制項EditTextWithDel

來源:互聯網
上載者:User

標籤:ext.get   net   phone   create   span   graph   記錄   hone   lob   

記錄下一個非常有用的小控制項EditTextWithDel。就是在Android系統的輸入框右邊增加一個小表徵圖。點擊小表徵圖能夠清除輸入框裡面的內容,由於Android原生EditText不具備此功能,所以要想實現這一功能我們須要重寫EditText。
例如以下:

基本的思路就是為右邊的圖片設定監聽。點擊右邊的圖片清除輸入框的內容並隱藏刪除表徵圖,由於我們不能直接給EditText設定點擊事件,所以我們用記住我們按下的位置來類比點擊事件,用輸入框的的onTouchEvent()方法來類比.

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;/** * @author: adan * @description: 自己定義帶有刪除功能的EditText * @projectName: EditTextWithDelDome * @date: 2016-02-28 * @time: 23:34 */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;            if (rect.contains(eventX, eventY))                setText("");        }        return super.onTouchEvent(event);    }    @Override    protected void finalize() throws Throwable {        super.finalize();    }}

setDrawable()方法,setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)來在上、下、左、右設定表徵圖,假設不想在某個地方顯示,則設定為null。
接下來我們來使用它設定Activity的布局。一個我們自己定義的輸入框,一個button

<?

xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://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>

然後就是介面代碼的編寫。主要測試下輸入框

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();            }        });    }}

Dome下載

Android 帶清除功能的輸入框控制項EditTextWithDel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.