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

自定義 Android 組件(二):用「組合」的方式做一個帶明文開關的密碼輸入框

編輯:關於 Android 程式設計

Android 裡所有控件都脫胎自 android.view.View,而絕大多數布局類則是 ViewGroup 的後代。因此自定義組件大致有兩條路:一條是繼承 View,自己拿畫筆和畫布從零繪製;另一條是繼承某個 ViewGroup 子類,把現成控件「拼」起來。本文走第二條路。

目標很具體:做一個 PassWordView,右側放一個 CheckBox,勾選就明文顯示密碼,取消勾選就回到圓點遮罩。

一、實現步驟

  1. 設計 PassWordView 的結構與外觀;
  2. 在 res/values/attrs.xml 中聲明自定義屬性;
  3. 編寫 PassWordView 類,完成內部控件的組合與事件綁定;
  4. 在布局裡使用它並設置屬性;
  5. 在 Activity 中讀取它的內容。

二、為什麼選 LinearLayout

輸入框和 CheckBox 需要並排一行,用 LinearLayout 最省事。文中把 EditText 稱為「左組件」,CheckBox 稱為「右組件」,兩者通過 layout_weight 分配父容器空間。

三、自定義樣式屬性

文件位置: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>

這裡有個小技巧:像 inputType 這種系統已有、含義清晰的屬性,直接引用即可,寫法上注意帶上 android: 前綴。

四、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 void initProperty(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PassWordView);
        leftComponentWeight = ta.getFloat(R.styleable.PassWordView_left_component_weight, 5.0f);
        rightComponentWeight = ta.getFloat(R.styleable.PassWordView_right_component_weight, 1.0f);
        inputType = ta.getInt(R.styleable.PassWordView_android_inputType,
                InputType.TYPE_TEXT_VARIATION_PASSWORD);
        ta.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();
    }

    public EditText getPassWordEditText() {
        return mPassWordEditText;
    }

    /** 勾選明文,取消勾選遮罩 */
    private void addCheckBoxListener() {
        mShowCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPassWordEditText.setTransformationMethod(isChecked
                        ? HideReturnsTransformationMethod.getInstance()
                        : PasswordTransformationMethod.getInstance());
            }
        });
    }
}

關鍵點在於 TransformationMethod:切換實現類就能在明文與密文之間無痛切換,不需要碰 setInputType,也不會丟失光標位置。

五、在布局中使用

文件:activity_combine_view.xml

<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>

自定義屬性的命名空間要用 res-auto,這是很多人第一次寫自定義控件最容易踩的坑。

六、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 = findViewById(R.id.password_view);
        mPassWordTextView = findViewById(R.id.password_text_view);
    }

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

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

七、小結

組合式自定義組件的優勢很明顯:實現成本低、可複用性強,還能借力原有控件的成熟能力。只有在現有控件確實滿足不了需求時,才值得去走「自己繪製」那條最原始也最靈活的路。

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