在TextInputLayout中切换密码时回调

问题描述 投票:1回答:1

我已经为我的密码字段选择了TextInputEditText,以使用切换密码功能。

这是我的xml代码:

        <com.google.android.material.textfield.TextInputLayout
        android:layout_width="@dimen/login_width"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/password_margin_top"
        app:hintEnabled="false"
        app:passwordToggleDrawable="@drawable/password_toggle_drawable"
        app:passwordToggleEnabled="true">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/my_login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif"
            android:hint="@string/password"
            android:inputType="textPassword"
            android:nextFocusDown="@+id/my_login_login"
            android:padding="@dimen/field_padding" />
    </com.google.android.material.textfield.TextInputLayout>

我必须对切换密码进行其他一些布局更改。在TextInputLayout中是否有任何回调可用于此?

android android-textinputlayout android-textinputedittext
1个回答
0
投票

您可以在setEndIconOnClickListener上呼叫TextInputLayout

textInputLayout.setEndIconOnClickListener { v ->
    // Layout changes here
}

但是,这会删除负责切换密码转换方法的点击侦听器。我建议只复制PasswordToggleEndIconDelegate中的点击监听器代码,然后在顶部添加您自己的功能:

textInputLayout.setEndIconOnClickListener {
    val editText: EditText? = textInputLayout.editText
    // Store the current cursor position
    val selection = editText?.selectionEnd ?: 0

    // Check for existing password transformation
    val hasPasswordTransformation = editText?.transformationMethod is PasswordTransformationMethod;
    if (hasPasswordTransformation) {
        editText?.transformationMethod = null
    } else {
        editText?.transformationMethod = PasswordTransformationMethod.getInstance()
    }

    // Restore the cursor position
    editText?.setSelection(selection)

    // Add additional functionality here
}

0
投票

您可以使用:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/til_password"

和:

password = findViewById(R.id.til_password);
password.setEndIconOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View view) {
    //....
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.