編輯:關於 Android 程式設計
簡書 App 是我很喜歡的一款軟體,這次就來仿一下它的登入框。先看效果:

互動細節有兩個:輸入內容後右側出現叉號可一鍵清空;密碼框右側的眼睛圖示可切換明文/密文顯示。
標準 EditText 無法直接為複合 Drawable(也就是 drawableLeft、drawableRight 這些)掛上點擊事件,必須自行攔截 onTouchEvent 判斷觸碰位置是否落在圖示區域。整個自定義類別要處理四件事:
package lyf.myimgedittextdemo;
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.widget.EditText;
/**
* 自定義的 EditText,右邊帶圖片,可以設置點擊事件
*/
public class ImgEditText extends EditText implements TextWatcher {
// 控件左邊的圖片
private Drawable leftDrawable = null;
// 控件右邊的圖片
private Drawable rightDrawable = null;
// 控件是否有焦點
private boolean hasFoucs;
private IMyRightDrawableClick mightDrawableClick;
public ImgEditText(Context context) {
this(context, null);
}
public ImgEditText(Context context, AttributeSet attrs) {
// 這個構造方法很重要,不加的話很多屬性不能在 XML 裡定義
this(context, attrs, android.R.attr.editTextStyle);
}
public ImgEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
// 初始化基本圖片
private void init() {
// 獲取 Drawable 的圖片集合
Drawable[] drawables = getCompoundDrawables();
leftDrawable = drawables[0];
rightDrawable = drawables[2];
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
// 設置輸入框裡面內容發生改變的監聽
addTextChangedListener(this);
}
// 設置顯示圖片的大小
public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
Drawable right, Drawable bottom) {
super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
// 這裡只要改後面兩個參數就好,一個寬一個高
if (left != null) {
left.setBounds(0, 0, 50, 50);
}
if (right != null) {
right.setBounds(0, 0, 50, 50);
}
if (top != null) {
top.setBounds(0, 0, 100, 100);
}
if (bottom != null) {
bottom.setBounds(0, 0, 100, 100);
}
setCompoundDrawables(left, top, right, bottom);
}
// 光標焦點變化時判斷
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
this.hasFoucs = focused;
if (focused) {
setImageVisible(getText().length() > 0);
} else {
setImageVisible(false);
}
}
// 設置清除圖標的顯示與隱藏
protected void setImageVisible(boolean flag) {
// 如果當前右側有圖片則覆蓋右側的圖片,如果沒有還是顯示原來的圖片
if (getCompoundDrawables()[2] != null) {
rightDrawable = getCompoundDrawables()[2];
}
if (flag) {
setCompoundDrawables(getCompoundDrawables()[0], null, rightDrawable, null);
} else {
setCompoundDrawables(getCompoundDrawables()[0], null, null, null);
}
}
// 文本框監聽事件
@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if (hasFoucs) {
if (text.length() > 0) {
setImageVisible(true);
} else {
setImageVisible(false);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
/**
* 因為不能直接給 EditText 設置點擊事件,所以我們記住按下的位置來模擬點擊事件。
* 當按下的位置落在
* EditText 寬度 - 圖標到右邊的間距 - 圖標寬度
* 與
* 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) {
// 調用點擊事件(外部實現)
mightDrawableClick.rightDrawableClick();
}
}
}
return super.onTouchEvent(event);
}
// 設置右側按鈕的點擊事件,外部調用時實現該方法
public void setDrawableClick(IMyRightDrawableClick myMightDrawableClick) {
this.mightDrawableClick = myMightDrawableClick;
}
// 自定義接口(實現右邊圖片點擊事件)
public interface IMyRightDrawableClick {
void rightDrawableClick();
}
// 允許外部修改右側顯示的圖片
public void setRightDrawable(Drawable drawable) {
rightDrawable = drawable;
setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
}
}
為什麼要重寫 setCompoundDrawablesWithIntrinsicBounds()?系統預設會用圖片素材的原始尺寸來繪製,圖片一大就會撐爆佈局。重寫後強制把 bounds 設成 50×50,尺寸就固定了。注意這裡的最終呼叫是 setCompoundDrawables() 而非帶 IntrinsicBounds 的版本——因為 bounds 已經手動設好,再走一次系統計算反而會被覆蓋掉。
三參數的建構子不能省。this(context, attrs, android.R.attr.editTextStyle) 這一行是關鍵。少了它,XML 裡寫的屬性(提示文字、輸入方式、drawable 等)會大量失效,這是自定義 View 最常見的坑之一。
觸碰判斷的座標邏輯。用 event.getX() 判斷是否落在「總右內距」與「右內距」之間,本質上是在算 Drawable 佔據的那塊矩形區域。這個做法簡單有效,但要注意:如果使用者點在邊界附近又稍微滑動,可能觸發不完全符合預期。更嚴謹的做法是用 event.getX() > (getWidth() - getTotalPaddingRight())event.getY() 的範圍一併判斷,避免長條形區域誤觸。
佈局檔直接寫全限定類名即可:
<lyf.myimgedittextdemo.ImgEditText
android:id="@+id/pwdIet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@null"
android:drawableLeft="@mipmap/mm_image"
android:drawableRight="@mipmap/eye_normal"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="5dp"
android:drawablePadding="15dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:hint="密碼"
android:inputType="numberPassword" />
眼睛圖示的切換邏輯寫在 Activity 裡,透過 setDrawableClick() 註冊回呼:
pwdIet = (ImgEditText) this.findViewById(R.id.pwdIet);
pwdIet.setDrawableClick(new ImgEditText.IMyRightDrawableClick() {
@Override
public void rightDrawableClick() {
if (isHidden) {
// 設置 EditText 文本為可見的
pwdIet.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
pwdIet.setRightDrawable(getResources().getDrawable(R.mipmap.eye_selected));
} else {
// 設置 EditText 文本為隱藏的
pwdIet.setTransformationMethod(PasswordTransformationMethod.getInstance());
pwdIet.setRightDrawable(getResources().getDrawable(R.mipmap.eye_normal));
}
isHidden = !isHidden;
pwdIet.postInvalidate();
// 切換後將 EditText 光標置於末尾
CharSequence charSequence = pwdIet.getText();
if (charSequence instanceof Spannable) {
Spannable spanText = (Spannable) charSequence;
Selection.setSelection(spanText, charSequence.length());
}
}
});
最後那段「把光標移到尾端」的處理很細膩,也很容易被忽略。因為 setTransformationMethod() 會重建文字顯示的 Spannable,導致光標跳回開頭。不處理的話,使用者切換一次明文,游標就跑到第一個字前面,體驗相當糟。
如果要在專案裡長期使用,這份實作有幾個方向可以調整。
第一,把圖示尺寸與邊距抽成自定義屬性(用 declare-styleable),而不是像範例那樣把 50、100 寫死在程式碼裡,這樣同一個類別才能在不同場景下呈現不同尺寸。
第二,setImageVisible() 的顯示條件目前是「有焦點且內容非空」。有些設計稿要求「只要內容非空就顯示叉號」,差別只在要不要判斷 hasFoucs,改一行即可。
第三,Android 已提供 TextInputLayout 搭配 TextInputEditText,並內建密碼切換圖示(app:passwordToggleEnabled="true")。如果只是要密碼眼睛功能,直接用官方元件會省下不少功夫;需要高度客製的清空按鈕或特殊樣式時,才值得走自定義 View 這條路。
以上就是這個仿簡書登入框的完整實作。核心不難,難的是把焦點變化、文字變化、觸碰判定這三條時序理清楚,並記得處理光標位置這類細節。
自定义 Adapter 结合 LayoutInflater 实现复杂 ListView 布局
看到标题这么长,大家可能有点抓狂。什么是布局泵?如何编辑每一个模板?什么又是自定义 Adapter?别着急,通过本文的学习,这些疑问都会一一解开。 逻辑
使用 SpannableStringBuilder 實現圖文混排與「更多」效果
需求場景在許多內容型應用中,長文字需要限制顯示行數,超出部分以省略號表示,並在省略號後方加入「更多」圖示或文字,引導使用者展開完整內容。這種效果若只靠 TextView
Android 崩潰防護:全域 UncaughtException 捕捉與日誌落地
實專案裡,導致 App 閃退的異常多到數不完。開發階段我們可以靠 logcat 逐一 debug,但有些問題藏得很深——裝置碎片化、系統版本差異、各家 ROM 的客製行為
Android 中彈出輸入法導致內容上移的問題排查
前言:某天寫程式時,筆者想達到這樣的效果——點擊某個 EditText 時,只有該區域上移,標題區域保持不動。如下圖所示: 在 AndroidManifest 中,我把