今天學習了自定義控件,然后自己做了一個用戶登錄小控件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(注:原作者在清除圖標監聽上沒有考慮豎直方向,另外,輸入框的晃動效果也沒有實現,自己查閱了一些資料把這兩個功能都添加了上去)