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

登陸界面細節實戰:自定義可一鍵清除的 EditText 與抖動動畫

編輯:關於 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 加上聲明式狀態描述的自然結果。

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