How to show and hide Android Edit Text Preference?

333 Views Asked by At

I just wish to know how can i show or hide edit text preference that i use to add username and password.

can i use such kind of feature here -to enable or disable a button in xml for edit text preference as well

ImageButton ready = (ImageButton) findViewById(R.id.ready);

ready.setVisibility(View.INVISIBLE);

<EditTextPreference
    android:key="password"
    android:title="@string/pref_title_password"
    android:defaultValue="@string/pref_default_password"
    android:selectAllOnFocus="true"
    android:inputType="textPassword"
    android:capitalize="words"
    android:singleLine="true"
    android:maxLines="1" />
1

There are 1 best solutions below

1
D. Sikilai On

EditTextPreference is not derived from android.view.View, therefore setVisibilty will not work. Instead do as follows:-

  • get the underlying EditText.
  • call setVisibility from there. Or proceed further by getting the parent view and calling the method from there.

    Compiling our explanation, yield should be as follows:-
    get the preference:-

    EditTextPreference pswd=(EditTextPreference)findPreference("password");
    

    then:-

    pswd.getEditText().setVisibility(View.INVISIBLE);
    

    or generally:-

    ViewParent parent=pswd.getEditText().getParent();
    if(parent instanceof View)
    ((View)parent).setVisibility(View.INVISIBLE);
    else pswd.getEditText().setVisibility(View.INVISIBLE);
    

    Edit:
    The method findPreference is found in android.preference.PreferenceActivity or android.preference.PreferenceFragment. Which means you need to call it from a fragment or activity that is derived from any of them - Your activity should extend any of them.
    I have not tested the above snippets yet but feel free to edit correction or comment.