Android 帶清除功能的輸入框控制項EditText,框控制項edittext

來源:互聯網
上載者:User

Android 帶清除功能的輸入框控制項EditText,框控制項edittext

今天學習了自訂控制項,然後自己做了一個使用者登入小控制項EditText,就是在Android系統的輸入框右邊加入一個小表徵圖,點擊小表徵圖可以清除輸入框裡面的內容,但是Android原生EditText不具備此功能,所以要想實現這一功能我們需要重寫EditText。

先說明一下,我是用Android studio寫的,代碼已經共用到我的github上了,有需要的可以去下載。

我們可以為我們的輸入框在上下左右設定圖片,所以我們可以利用屬性android:drawableRight設定我們的刪除小表徵圖,

 

 

這裡設定了左邊和右邊的圖片,如果我們能為右邊的圖片設定監聽,點擊右邊的圖片清除輸入框的內容並隱藏刪除表徵圖,這樣子這個小功能就迎刃而解了,可是 Android並沒有給允許我們給右邊小表徵圖加監聽的功能,這時候你是不是發現這條路走不通呢,其實不是,我們可能類比點擊事件,用輸入框的的 onTouchEvent()方法來類比,

 

當我們觸摸抬起(就是ACTION_UP的時候)的範圍  水平方向大於輸入框左側到清除表徵圖左側的距離,小與輸入框左側到清除圖片右側的距離,在豎直方向大於輸入框上頂部到清除表徵圖上側的距離,小於輸入框下底部到清除表徵圖的距離,我們則認為是點擊清除圖片,只要給清除小表徵圖就上了監聽,同時也給輸入框設定了晃動效果,當沒有輸入賬戶時,點擊登入,就會實現輸入框的晃動。下面貼一下代碼。(代碼中有很詳細的注釋)

 

package com.tony.clearedittext;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.view.MotionEvent;import android.view.View;import android.view.animation.Animation;import android.view.animation.CycleInterpolator;import android.view.animation.TranslateAnimation;import android.widget.EditText;import java.util.jar.Attributes;/** * Created by Cheng Bao on 2015/6/17. */public class ClearEditText extends EditText implements View.OnFocusChangeListener,TextWatcher {    /**     * 刪除按鈕的引用     */    private Drawable mClearDrawable;    private Context context;    /**     * 控制項是否有焦點     */    private boolean hasFocus;    public ClearEditText(Context context) {        this(context,null);//        super(context);//        this.context = context;//        init();    }    public ClearEditText(Context context,AttributeSet attrs){        //這裡構造方法也很重要,不加這個很多屬性不能再XML裡面定義        this(context, attrs, android.R.attr.editTextStyle);    }    public ClearEditText(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        init();    }    private void init() {        //擷取EditText的DrawableRight,假如沒有設定我們就使用預設的圖片        mClearDrawable = getCompoundDrawables()[2];        if (mClearDrawable == null) {            mClearDrawable = getResources().getDrawable(R.drawable.delete_selector);        }        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());        //預設設定隱藏表徵圖        setClearIconVisible(false);        //設定焦點改變的監聽        setOnFocusChangeListener(this);        //設定輸入框裡面內容發生改變的監聽        addTextChangedListener(this);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        if (mClearDrawable != null && event.getAction() == MotionEvent.ACTION_UP) {            int x = (int) event.getX();            //判斷觸摸點是否在水平範圍內            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight())) &&                    (x < (getWidth() - getPaddingRight()));            //擷取刪除表徵圖的邊界,返回一個Rect對象            Rect rect = mClearDrawable.getBounds();            //擷取刪除表徵圖的高度            int height = rect.height();            int y = (int) event.getY();            //計算表徵圖底部到控制項底部的距離            int distance = (getHeight() - height) / 2;            //判斷觸摸點是否在豎直範圍內(可能會有點誤差)            //觸摸點的縱座標在distance到(distance+表徵圖自身的高度)之內,則視為點中刪除表徵圖            boolean isInnerHeight = (y > distance) && (y < (distance + height));            if (isInnerHeight && isInnerWidth) {                this.setText("");            }        }        return super.onTouchEvent(event);    }    /**     * 設定清除表徵圖的顯示與隱藏,調用setCompoundDrawables為EditText繪製上去     *     * @param visible     */    private void setClearIconVisible(boolean visible) {        Drawable right = visible ? mClearDrawable : null;        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1],                right, getCompoundDrawables()[3]);    }    /**     * 當ClearEditText焦點發生變化的時候,判斷裡面字串長度設定清除表徵圖的顯示與隱藏     */    @Override    public void onFocusChange(View v, boolean hasFocus) {        this.hasFocus = hasFocus;        if (hasFocus) {            setClearIconVisible(getText().length() > 0);        } else {            setClearIconVisible(false);        }    }    /**     * 當輸入框裡面內容發生變化的時候回調的方法     */    @Override    public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {        if (hasFocus) {            setClearIconVisible(text.length() > 0);        }    }    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {    }    @Override    public void afterTextChanged(Editable s) {    }    /**     * 設定晃動動畫     */    public void setShakeAnimation() {        this.startAnimation(shakeAnimation(5));    }    /**     * 晃動動畫     *     * @param counts 1秒鐘晃動多少下     * @return     */    public static Animation shakeAnimation(int counts) {        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);        translateAnimation.setInterpolator(new CycleInterpolator(counts));        translateAnimation.setDuration(1000);        return translateAnimation;    }}

 

  • setClearIconVisible() 方法,設定隱藏和顯示清除表徵圖的方法,這裡不是調用setVisibility()方法,setVisibility()這個方法是針對View的, 我們可以調用setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)來設定上下左右的表徵圖
  • setOnFocusChangeListener(this) 為輸入框設定焦點改變監聽,如果輸入框有焦點,我們判斷輸入框的值是否為空白,為空白就隱藏清除表徵圖,否則就顯示
  • addTextChangedListener(this) 為 輸入框設定內容改變監聽,其實很簡單呢,當輸入框裡面的內容發生改變的時候,我們需要處理顯示和隱藏清除小表徵圖,裡面的內容長度不為0我們就顯示,否是就 隱藏,但這個需要輸入框有焦點我們才改變顯示或者隱藏,為什麼要需要焦點,比如我們一個登陸介面,我們儲存了使用者名稱和密碼,在登陸介面 onCreate()的時候,我們把我們儲存的密碼顯示在使用者名稱輸入框和密碼輸入框裡面,輸入框裡面內容發生改變,導致使用者名稱輸入框和密碼輸入框裡面的清 除小表徵圖都顯示了,這顯然不是我們想要的效果,所以加了一個是否有焦點的判斷
  • setShakeAnimation(),這個方法是輸入框左右抖動的方法,當使用者名稱錯誤,輸入框就在哪裡抖動,其實主要是用到一個移動動畫,然後設定動畫的變動率為正弦曲線

接下來我們來使用它,Activity的布局,兩個我們自訂的輸入框,一個按鈕

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    android:background="#95CAE4"    tools:context=".MainActivity">    <com.tony.clearedittext.ClearEditText        android:id="@+id/username"        android:layout_marginTop="60dp"        android:background="@drawable/login_edittext_bg"        android:drawableLeft="@drawable/icon_user"        android:layout_marginLeft="10dip"        android:layout_marginRight="10dip"        android:singleLine="true"        android:drawableRight="@drawable/delete_selector"        android:hint="輸入使用者名稱"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <com.tony.clearedittext.ClearEditText        android:id="@+id/password"        android:layout_marginLeft="10dip"        android:layout_marginRight="10dip"        android:layout_marginTop="10dip"        android:drawableLeft="@drawable/account_icon"        android:hint="輸入密碼"        android:singleLine="true"        android:password="true"        android:drawableRight="@drawable/delete_selector"        android:layout_below="@+id/username"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="@drawable/login_edittext_bg"        />    <Button        android:id="@+id/login"        android:layout_marginLeft="10dip"        android:layout_marginRight="10dip"        android:background="@drawable/login_button_bg"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textSize="18sp"        android:textColor="@android:color/white"        android:layout_below="@+id/password"        android:layout_marginTop="25dp"        android:text="登入"        /></RelativeLayout>

然後就是介面代碼的編寫,主要是測試輸入框左右晃動

 

package com.tony.clearedittext;import android.app.Activity;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.text.TextUtils;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity {    private Toast mToast;    private Button mButton;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        final ClearEditText username = (ClearEditText) findViewById(R.id.username);        final ClearEditText password = (ClearEditText) findViewById(R.id.password);        mButton = (Button) findViewById(R.id.login);        mButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (TextUtils.isEmpty(username.getText())){                    //設定晃動                    username.setShakeAnimation();                    //設定提示                    showToast("使用者名稱不可為空!");                    return;                }                if (TextUtils.isEmpty(password.getText())){                    password.setShakeAnimation();                    showToast("密碼不可為空!");                    return;                }            }        });    }    /**     * 顯示Toast訊息     * @param msg     */    private void showToast(String msg) {        if (mToast == null){            mToast = Toast.makeText(this,msg,Toast.LENGTH_SHORT);        }else{            mToast.setText(msg);        }        mToast.show();    }}

 

如下:

項目源碼:https://github.com/tonycheng93/Android-CustomLoginDemo

又需要的小夥伴或者是正在學習的趕緊那去吧,呵呵

在學習的過程中CSDN上的一篇文章給了我很大的協助,能實現這個自訂控制項很大程度上都是借鑒這篇優秀的部落格分享:http://blog.csdn.net/xiaanming/article/details/11066685(註:原作者在清除表徵圖監聽上沒有考慮豎直方向,另外,輸入框的晃動效果也沒有實現,自己查閱了一些資料把這兩個功能都添加了上去)

 

聯繫我們

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