常见场景,点击某个按钮,切换密码输入框的可见性。
布局输入框部分关键代码:
<LinearLayout style="@style/InputPanel"
android:layout_marginTop="5dp">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_menu_lock"/>
<EditText android:id="@+id/password_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/input_new_password"
style="@style/InputEdit.TextPassword"
android:background="@null"
android:layout_marginLeft="10dp"/>
<ImageView android:id="@+id/eye_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_menu_eye"/>
</LinearLayout>
Activity中控制代码:
@BindView(R.id.password_et)
EditText passwordEt;
@OnClick(R.id.eye_btn)
void onEyeBtnClick() {
TransformationMethod method = passwordEt.getTransformationMethod();
if (method == HideReturnsTransformationMethod.getInstance()) {
passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
// 保证切换后光标位于文本末尾
Spannable spanText = passwordEt.getText();
if (spanText != null) {
Selection.setSelection(spanText, spanText.length());
}
}