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

動手做一個 QQ 風格登入頁:自訂 EditText 背景與清空按鈕

編輯:關於 Android 開發

從一個登入頁練完 UI 基本功

登入頁看似簡單,卻涵蓋了自訂背景、焦點控制、即時監聽與可見性切換等一連串 UI 技巧。本文以 QQ 風格的登入畫面為題,把這些要點逐一走過。

過程中會碰到的幾個問題

1. 為 EditText 自訂背景。

2. 執行時 EditText 自動獲得焦點,導致鍵盤搶走畫面。

3. 提示文字應該在「獲得焦點時」清空,而不是等到使用者開始輸入才消失。

4. 清空按鈕的出現時機:必須同時滿足「已取得焦點」與「有輸入內容」。

版面配置(問題 2)

<!-- android:focusable="true"
     android:focusableInTouchMode="true"
     這兩行把 EditText 預設的行為截斷了! -->
<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="#ECEDF1"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context="com.dragon.android.qqlogin.MainActivity$PlaceholderFragment" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="40dp"
        android:src="@drawable/a" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView1"
        android:ems="10"
        android:background="@drawable/bg_edittext"
        android:inputType="textPersonName"
        android:gravity="center"
        android:textColor="#6A6A6C"
        android:hint="@string/inaccount"
        android:textColorHint="#ECEDDD">
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editText1"
        android:ems="10"
        android:background="@drawable/bg_edittext"
        android:inputType="textPassword"
        android:gravity="center"
        android:textColor="#6A6A6C"
        android:hint="@string/inpwd"
        android:textColorHint="#ECEDDD" >
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/editText2"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_button"
        android:text="@string/button"
        android:gravity="center"
        android:textColor="#F9FAFB" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:padding="10dp" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/faillogin"
            android:textColor="#0EB1EF" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="@string/regist"
            android:textColor="#0EB1EF" />
    </LinearLayout>

    <Button
        android:id="@+id/button2"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:layout_alignTop="@id/editText1"
        android:layout_marginTop="15dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:background="@drawable/clear"
        android:visibility="invisible" />

    <Button
        android:id="@+id/button3"
        android:layout_width="16dp"
        android:layout_height="16dp"
        android:layout_alignTop="@id/editText2"
        android:layout_marginTop="15dp"
        android:layout_alignLeft="@+id/button2"
        android:background="@drawable/clear"
        android:visibility="invisible" />

</RelativeLayout>

根配置的 focusable 與 focusableInTouchMode 是解題關鍵。預設情況下,Activity 啟動時焦點會自動落到畫面上第一個可聚焦的元件,也就是帳號輸入框,鍵盤便立刻彈出遮住版面。讓根配置搶走初始焦點,就能避免這個惱人的行為。

另外注意清空按鈕用的是 android:visibility="invisible" 而非 gone。兩者差異在於 invisible 仍佔據版面空間,因此按鈕位置固定不會跳動;若用 gone,元素會從版面流程中移除,反而可能造成位移。

自訂背景(問題 1)

Button 的背景 bg_button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android" >
    <stroke android:width="1px" android:color="#00ACED" />
    <solid android:color="#00ACED" />
    <corners android:radius="10dp" />
</shape>

EditText 的背景 bg_edittext:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android" >
    <stroke android:width="1px" android:color="#ECEDF1" />
    <solid android:color="#F9FAFB" />
    <corners android:radius="10dp" />
    <padding
        android:top="10dp"
        android:bottom="10dp"/>
</shape>

用 shape 標籤畫圓角矩形,比切九宮格圖片乾淨得多,也不會因螢幕密度不同而模糊。自訂 EditText 背景時還有一個常忽略的細節:預設的 EditText 會帶有一條底線與左右內距,換成自訂背景後這些都消失了,因此需要自行用 padding 補回基本的呼吸空間。

字串資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">qqloginnew</string>
    <string name="action_settings">Settings</string>
    <string name="button">登錄</string>
    <string name="faillogin">無法登錄?</string>
    <string name="regist">新用戶注冊</string>
    <string name="inaccount">QQ號/手機號/郵箱</string>
    <string name="inpwd">密碼</string>
    <string name="sucess">登錄成功</string>
</resources>

把文字全部抽到 strings.xml 而非寫死在配置檔中,是多語言支援的前提,也是好習慣的起點。

MainActivity(問題 3、4)

package com.dragon.android.qqloginnew;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    private EditText editText1;
    private EditText editText2;
    private Button clearButton1;
    private Button clearButton2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
        clearButton1 = (Button) findViewById(R.id.button2);
        clearButton2 = (Button) findViewById(R.id.button3);

        // 對 EditText 進行焦點變更監聽
        editText1.setOnFocusChangeListener(new EditTextListener(clearButton1));
        editText2.setOnFocusChangeListener(new EditTextListener(clearButton2));

        // 對清空按鈕進行點擊監聽
        clearButton1.setOnClickListener(new ClearButtonListener());
        clearButton2.setOnClickListener(new ClearButtonListener());

        // 對 EditText 進行編輯監聽
        editText1.addTextChangedListener(new MyEditTextWatcher(editText1));
        editText2.addTextChangedListener(new MyEditTextWatcher(editText2));
    }

    /** 對 EditText 的內容進行實時監控 */
    class MyEditTextWatcher implements TextWatcher {

        private CharSequence temp;
        private EditText editText;

        public MyEditTextWatcher(EditText editText) {
            this.editText = editText;
        }

        // start 開始位置、count 被改變的內容數量、after 改變後的內容數量
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        // start 開始位置、before 改變前的內容數量、count 新增量
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            temp = s;
        }

        // 最終內容
        @Override
        public void afterTextChanged(Editable s) {
            if (temp.length() > 0) {
                if (editText == editText1) {
                    clearButton1.setVisibility(View.VISIBLE);
                } else if (editText == editText2) {
                    clearButton2.setVisibility(View.VISIBLE);
                }
            } else {
                if (editText == editText1) {
                    clearButton1.setVisibility(View.INVISIBLE);
                } else if (editText == editText2) {
                    clearButton2.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

    /** 清空按鈕點擊事件 */
    class ClearButtonListener implements OnClickListener {
        @Override
        public void onClick(View view) {
            if (view == clearButton1) {
                editText1.setText("");
            } else if (view == clearButton2) {
                editText2.setText("");
            }
        }
    }

    /** 焦點變更事件 */
    class EditTextListener implements OnFocusChangeListener {

        private Button clear;

        public EditTextListener(Button clear) {
            this.clear = clear;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText textView = (EditText) v;
            String hint;
            if (hasFocus) {
                // 取得焦點時若內容不為空,清空按鈕可見
                if (!textView.getText().toString().equals("")) {
                    clear.setVisibility(View.VISIBLE);
                }
                hint = textView.getHint().toString();
                // 把 hint 暫存到 tag,再清空 hint —— 這樣提示文字會在聚焦時消失
                textView.setTag(hint);
                textView.setHint("");
            } else {
                // 失去焦點時清空按鈕隱藏,並還原 hint
                clear.setVisibility(View.INVISIBLE);
                hint = textView.getTag().toString();
                textView.setHint(hint);
            }
        }
    }
}

幾個值得拆解的技巧

用 setTag() 暫存 hint。這是解決問題 3 的核心手法。需求是「聚焦時提示文字消失」,而 setHint("") 一旦執行,原本的提示內容就沒了。作者的做法是先把 hint 存進 View 的 tag,聚焦時設為空字串,失焦時再從 tag 取回還原。簡潔且不需要額外變數。

TextWatcher 三個方法的分工。beforeTextChanged 拿到的是「改變前」的內容,onTextChanged 拿到的是「改變後」的內容,afterTextChanged 則是最終結果。範例在 onTextChanged 中把 s 存下來,再在 afterTextChanged 中據以判斷,是相當典型的用法。

為什麼要檢查 temp 而非直接看 Editable。其實在 afterTextChanged(Editable s) 中直接用 s.length() 判斷即可,範例多繞了一層。這不算錯,但可以更精簡。

圖片素材

a.png clear.png

這是一個初步可用的登入界面。真實專案中,登入鈕的點擊還需要加上表單驗證、忙碌狀態鎖定與失敗提示,並把密碼以加密通道傳送——明文傳密碼在任何環境下都是不可接受的。

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