編輯:關於 Android 程式設計
Android 裡所有控件都脫胎自 android.view.View,而絕大多數布局類則是 ViewGroup 的後代。因此自定義組件大致有兩條路:一條是繼承 View,自己拿畫筆和畫布從零繪製;另一條是繼承某個 ViewGroup 子類,把現成控件「拼」起來。本文走第二條路。
目標很具體:做一個 PassWordView,右側放一個 CheckBox,勾選就明文顯示密碼,取消勾選就回到圓點遮罩。

res/values/attrs.xml 中聲明自定義屬性;輸入框和 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: 前綴。
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,這是很多人第一次寫自定義控件最容易踩的坑。
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。
組合式自定義組件的優勢很明顯:實現成本低、可複用性強,還能借力原有控件的成熟能力。只有在現有控件確實滿足不了需求時,才值得去走「自己繪製」那條最原始也最靈活的路。
Android Studio 中查看類繼承關係與 Scope 自訂設定
查看類繼承關係的快捷鍵是 F4,在 Android Studio 常用快捷鍵那篇已經提過。今天要談的是 F4 帶出的那個視窗上有哪些可設定的項目——這塊功能相對冷門,但同
Android 3G 調機筆記:基於 rild 實現自動撥號與斷線重連
本文記錄在 Android 平台上實現 3G 自動撥號的做法。思路是複用系統自帶的 rild 服務——rild 由 init 守護,正常情況下殺不死,因此只要讓它承擔撥號
深入透徹理解 Android Activity 生命週期
今天為大家詳細拆解 Android 中 Activity 的生命週期。我希望自己的講解不同於網上那些多半只是翻譯官方 API、過於籠統的文章——相信你讀完會有所收穫,但未
COCOS2D-X 實作:C++ 透過 JNI 呼叫 Android Java 方法
在 COCOS2D-X 中,C++ 邏輯若需要呼叫 Android Java 功能,例如 Toast、系統服務或平台 API,可透過 JNI 完成。以下以 HelloCp