編輯:關於 Android 程式設計
登陸框的體驗往往藏在細節裡:有內容時自動出現一鍵清空按鈕,密碼填錯時輸入框抖動提示。本文用一個自定義 ClearEditText 把這兩個效果一次實現。
效果預覽

一、自定義 ClearEditText
思路並不複雜:在 EditText 的右側複合圖形區域放一個清除圖標,通過 TextWatcher 監聽輸入變化控制它的顯示,再通過 onTouchEvent 判斷點擊是否落在圖標範圍內來清空文本。
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) {
// 這個構造方法很重要,缺了它很多屬性無法在 XML 中定義
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.selector_ic_delete);
}
// getIntrinsicWidth 返回的是 Drawable 的固有寬度
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
mClearDrawable.getIntrinsicHeight());
setClearIconVisible(false);
setOnFocusChangeListener(this);
addTextChangedListener(this);
}
/**
* EditText 不支持直接給複合圖形設置點擊事件,
* 因此用「記住按下位置」的方式來模擬點擊:
* 當按下位置落在 [控件寬度 - 右內邊距 - 圖標寬度, 控件寬度 - 右內邊距]
* 這個區間內,就認為點擊了圖標。垂直方向不做判斷。
*/
@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);
}
}
/** 通過 setCompoundDrawables 控制圖標顯示與隱藏 */
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));
}
/**
* 構建抖動動畫
* @param counts 每秒晃動的次數
*/
public static Animation shakeAnimation(int counts) {
Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
translateAnimation.setInterpolator(new CycleInterpolator(counts));
translateAnimation.setDuration(1000);
return translateAnimation;
}
}
這裡有兩個容易踩坑的地方:一是必須實現帶 AttributeSet 的三參數構造方法,否則在 XML 中引用時會直接崩潰;二是 onTouchEvent 中判斷點擊區域時使用了 getTotalPaddingRight() 與 getPaddingRight() 的差值來推算圖標位置,這段邏輯與具体的 padding 設置相關,改布局時需要一併驗證。
二、Activity 代碼
登陸按鈕暫時只用 Toast 演示點擊效果:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
}
public void login(View view) {
Toast.makeText(this, "登陸", Toast.LENGTH_LONG).show();
}
}
三、布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffffff"
android:orientation="vertical"
android:padding="4.0dip" >
<com.xuliugen.clearedittext.ClearEditText
android:id="@+id/etxtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30.0dip"
android:drawableLeft="@drawable/icon_reg_name"
android:drawablePadding="10.0dip"
android:hint="使用郵箱登陸" />
<com.xuliugen.clearedittext.ClearEditText
android:id="@+id/etxtPwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20.0dip"
android:drawableLeft="@drawable/icon_reg_password"
android:drawablePadding="10.0dip"
android:hint="輸入登陸密碼"
android:inputType="textPassword" />
<Button
android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20.0dip"
android:onClick="login"
android:text="登陸" />
</LinearLayout>
四、配套的 selector 資源
登陸按鈕的背景,通過 shape 定義不同狀態下的圓角填充色:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="2.0dip" />
<solid android:color="@color/green_btn_color_disable" />
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle">
<corners android:radius="2.0dip" />
<solid android:color="@color/green_btn_color_pressed" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<corners android:radius="2.0dip" />
<solid android:color="@color/green_btn_color_normal" />
</shape>
</item>
</selector>
輸入框的背景 selector,用兩張不同狀態的九宮格圖片切換:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/input_bar_bg_active" android:state_focused="true"/>
<item android:drawable="@drawable/input_bar_bg_normal"/>
</selector>
其餘還需要準備清除圖標的 selector 以及各類 icon 資源。整體看下來,登陸界面那些讓人覺得「做得細」的交互,本質上都是自定義 View 加上聲明式狀態描述的自然結果。
Android 核心服務解析(一):Android 系統的啟動流程
從宏觀角度來看,Android 系統的啟動可分為兩部分:Linux 核心的啟動與 Android 系統的啟動。前者包含系統引導、核心與驅動程式,不在本文討論範圍;本文聚焦
訊號不穩別急著怪手機,Android 網路模式這樣設就好
不少 Android 手機都出現過訊號起伏、通話品質不穩的狀況。但仔細追究起來,問題往往不在硬件,而在於我們從來沒有認真設定過網路參數。 以聯通 WCDMA 制式的 An
Android 中使用 Pull 解析 XML 數據的完整示例
Pull 解析 XML 的方式與 SAX 大致相同,兩者都是基於事件驅動的。使用 Pull 解析 XML 通常需要以下幾個步驟: 1)通過 XMLPullParserFa
Android 消息機制重點整理:Looper、Handler、Message 與 MessageQueue
Android 的消息機制幾乎是面試必考,但更值得學的理由是它在實際開發中無處不在——非同步回調、線程通訊、延遲任務,背後都是這套東西。本文用問答形式把關鍵點逐一拆開。