Search code examples
c#androidxamarinandroid-edittext

KeyPress doesn't wokr for password EditText types


Why this code doesn't work on Xamarin.Android? It sould change the enable propertie for the botton if the field of the password is typed.

        EditText edit_user_001 = FindViewById<EditText>(Resource.Id.id_edit_user_001);
        EditText edit_password_001 = FindViewById<EditText>(Resource.Id.id_edit_password_001);
        Button btn_login_001 = FindViewById<Button>(Resource.Id.id_btn_login_001);

        edit_password_001.KeyPress += (sender, e) => {
            if (edit_user_001.Text.ToString().Equals("") | edit_password_001.Text.ToString().Equals("")){
                btn_login_001.Enabled = false;
            } else {
                btn_login_001.Enabled = true;
            }
        };

This is the .xml:

    <TextView
        android:id="@+id/id_txt_user_001"
        android:text="@string/txt_user_001"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/id_edit_user_001"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10.0dp"
        android:inputType="text"/>
    <TextView
        android:text="@string/txt_password_001"
        android:id="@+id/id_txt_password_001"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/id_edit_password_001"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10.0dp"
        android:inputType="textPassword"/>

android:inputType="textPassword creates conflict. If I changes for android:inputType="text it works fine. Is there and alternative or a solution?


Solution

  • android:inputType="textPassword creates conflict. If I changes for android:inputType="text it works fine. Is there and alternative or a solution?

    Yes, I encounter same problem for KeyPress when setting EditText android:inputType="textPassword". You can use TextChanged method to achieve the same effects.

     private void Password_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            if (username.Text.Equals("") || password.Text.Equals(""))
            {
                button.Enabled = false;
            }
            else
            {
                button.Enabled = true;
            }
        }