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

自定義 Android 組件:用組合方式打造可切換明文的密碼輸入框

編輯:關於 Android 開發

兩條自定義控件的路,選組合這條比較省力

Android 裡所有控件都繼承自 android.view.View,而 android.view.ViewGroup 是 View 最重要的子類,絕大多數布局類都從它衍生而來(可參考基於 API 21 的 View/Widget 類圖)。

自定義組件大致有兩個入口:一是直接繼承 View,拿畫筆和畫布自己-onDraw-繪製;二是繼承某個 View 子類,再把現成組件「組合」起來。本文走第二條路——做一個 PassWordView,讓密碼欄旁邊帶一個勾選框,勾上就看得到明文。

實作方式是繼承 LinearLayout,內部組合 EditText 與 CheckBox。

開發步驟

自定義組件這邊要做四件事:設計組件外觀、在 res/values/attrs.xml 宣告自定義屬性、實作 PassWordView 類別、補上事件與屬性設定。使用端則是兩步:在布局中放入組件並設定屬性,然後在 Activity 裡操作它。

一、宣告自定義樣式屬性

檔案位置:res/values/attrs.xml。這裡有個實用技巧——系統已定義過的屬性可以直接引用,不必自己重造。

<declare-styleable name="PassWordView">
    <!-- 直接沿用系統已定義、語意明確的屬性,不需要再寫 format -->
    <attr name="android:inputType"/>
    <!-- 以下為自定義屬性 -->
    <attr name="left_component_weight" format="float"/>
    <attr name="right_component_weight" format="float"/>
</declare-styleable>

命名上把 EditText 稱為 left component(左組件)、CheckBox 稱為 right component(右組件),再用權重決定兩者佔父容器空間的比例。

二、實作 PassWordView

public class PassWordView extends LinearLayout {

    private EditText mPassWordEditText;
    private CheckBox mShowCheckBox;
    private LinearLayout.LayoutParams mPassWordParams;
    private LinearLayout.LayoutParams mShowParams;
    private float leftComponentWeight;
    private float rightComponentWeight;
    private int inputType;

    public PassWordView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initProperty(context, attrs);
        initComponent(context);
    }

    private final void initProperty(Context context, AttributeSet attrs) {
        // 讀取 XML 上的設定值,未設定時使用預設值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PassWordView);
        leftComponentWeight  = typedArray.getFloat(R.styleable.PassWordView_left_component_weight, 5.0f);
        rightComponentWeight = typedArray.getFloat(R.styleable.PassWordView_right_component_weight, 1.0f);
        // 來自 Android 系統已定義的屬性
        inputType = typedArray.getInt(R.styleable.PassWordView_android_inputType,
                                      InputType.TYPE_TEXT_VARIATION_PASSWORD);
        typedArray.recycle();   // 別忘了回收
    }

    private void initComponent(Context context) {
        mPassWordEditText = new EditText(context);
        mPassWordEditText.setInputType(inputType);
        mPassWordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());

        mShowCheckBox = new CheckBox(context);

        // 以權重決定兩個子檢視佔父容器的比例
        mPassWordParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, leftComponentWeight);
        mShowParams     = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, rightComponentWeight);

        setOrientation(HORIZONTAL);   // 容器視圖,水平排列
        addView(mPassWordEditText, mPassWordParams);
        addView(mShowCheckBox, mShowParams);

        addCheckBoxListener();
    }

    /** 對外開放:取得輸入的密碼 */
    public String getPassWord() {
        return mPassWordEditText.getText().toString();
    }

    /** 對外開放:取得內部的 EditText,需要更細粒度控制時用 */
    public EditText getPassWordEditText() {
        return mPassWordEditText;
    }

    private final void addCheckBoxListener() {
        // 勾選 → 明文顯示;取消勾選 → 圓點遮罩
        mShowCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mPassWordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mPassWordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }
}

關鍵就在這兩個 TransformationMethod:PasswordTransformationMethod 把字元換成圓點,HideReturnsTransformationMethod 則原樣顯示。切換顯示與否不必重設 inputType,換 transformation method 即可,輸入法類型仍可獨立控制。

三、在布局中使用

檔案:activity_combine_view.xml。使用自定義命名空間 https://schemas.android.com/apk/res-auto 來傳入自定義屬性。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:passwordview="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <secondriver.viewlibrary.PassWordView
        android:id="@+id/password_view"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#565354"
        android:inputType="textPassword"
        android:padding="10dp"
        passwordview:left_component_weight="5.0"
        passwordview:right_component_weight="1.0" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onShowPassWord"
        android:text="獲取密碼" />

    <TextView
        android:id="@+id/password_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="顯示 password" />
</LinearLayout>

四、Activity 端取得數值

public class CombinePassWordViewActivity extends Activity {

    private PassWordView mPassWordView;
    private TextView mPassWordTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_combine_view);
        mPassWordView    = (PassWordView) findViewById(R.id.password_view);
        mPassWordTextView = (TextView) findViewById(R.id.password_text_view);
    }

    public void onShowPassWord(View view) {
        mPassWordTextView.setText(mPassWordView.getPassWord());
    }
}

別忘了在 AndroidManifest.xml 註冊這個 Activity。

小結

組合既有控件來拼出複雜組件,通常比自行繪製來得容易,還能直接享受元件重用的好處;只有在現有控件實在無法滿足需求時,才值得回到最原始也最靈活的 Canvas 繪製路線。自定義屬性 + TypedArray 這套搭配,則是讓自定義組件「像系統控件一樣好用」的關鍵。

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