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

自製 ClearEditText:為 Android 輸入框加上一鍵清除功能

編輯:關於 Android 程式設計

這次要分享一個實用的小元件 ClearEditText:在 Android 輸入框右側放上一個小圖示,點一下就能清空輸入內容。iOS 只要設定某個屬性就能做到,但 Android 原生的 EditText 並不具備這個能力,因此我們得自己改寫 EditText 來補上。由於可以替輸入框的上下左右各配置一張圖片,我們便用 android:drawableRight 放刪除圖示:

我這裡左右都放了圖片。若能替右側圖片掛上監聽,點擊就清空並隱藏圖示,功能便大功告成。但 Android 並不允許直接給右側小圖示掛監聽,這時也別急著放棄——我們可以改寫 onTouchEvent() 來模擬點擊:當手指抬起(ACTION_UP)的位置落在「輸入框左側到清除圖示左側」與「輸入框左側到清除圖示右側」之間,就判定為點擊了清除圖示。這裡暫不考慮垂直方向。先貼程式碼,再逐一說明。

 package com.example.clearedittext; import android.content.Context; 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; public class ClearEditText extends EditText implements View.OnFocusChangeListener, TextWatcher { private Drawable mClearDrawable; private boolean hasFoucs; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { 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 (event.getAction() == MotionEvent.ACTION_UP) { if (getCompoundDrawables()[2] != null) { boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight()) && (event.getX() < ((getWidth() - getPaddingRight()))); if (touchable) { this.setText(""); } } } return super.onTouchEvent(event); } @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFoucs = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if(hasFoucs){ setClearIconVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } public void setShakeAnimation(){ this.setAnimation(shakeAnimation(5)); } 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()(那是針對整個 View 的),而是用 setCompoundDrawables(left, top, right, bottom) 來控制四邊的圖示。

setOnFocusChangeListener(this):為輸入框掛上焦點變更監聽。取得焦點時判斷內容是否為空,空就隱藏圖示,否則顯示。

addTextChangedListener(this):為輸入框掛上內容變更監聽。內容長度不為 0 就顯示清除圖示,否則隱藏;但這裡多加了一層「是否有焦點」的判斷。原因是像登入畫面若預先填入已存的帳號密碼,onCreate 時內容變動會讓兩個輸入框的清除圖示都冒出來,這顯然不是我們想要的,所以才用焦點判斷來避免。

setShakeAnimation():讓輸入框左右抖動的效果。這類互動常出現在帳號錯誤時的提示上,原理是套一個平移動畫,並把變化率設為正弦曲線。

接著看怎麼使用。版面配置放了兩個自訂輸入框與一個按鈕:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#95CAE4"> <com.example.clearedittext.ClearEditText android:id="@+id/username" android:layout_marginTop="60dp" android:layout_width="fill_parent" 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_height="wrap_content" > </com.example.clearedittext.ClearEditText> <com.example.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_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/username" android:background="@drawable/login_edittext_bg" > </com.example.clearedittext.ClearEditText> <Button android:id="@+id/login" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:background="@drawable/login_button_bg" android:textSize="18sp" android:textColor="@android:color/white" android:layout_below="@+id/password" android:layout_marginTop="25dp" android:text="登錄" /> </RelativeLayout>

程式碼部分主要是測試輸入框的抖動效果:

 package com.example.clearedittext; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Toast mToast; @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); ((Button) findViewById(R.id.login)).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; } } }); } private void showToast(String msg){ if(mToast == null){ mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); }else{ mToast.setText(msg); } mToast.show(); } } 

執行後如下圖所示:

以上就是 ClearEditText 的完整實作,是不是很想把它放進自己的專案裡呢?希望對你的 Android 開發有所幫助。

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