How to call ok button in EditTextPreference

I have an EditTextPreference in PreferenceActivity . When the user clicks the EditTextPreference button, you will see a dialog. The user can enter a value in the dialog box, and the OK and Cancel buttons in the dialog box. I want to trigger a click ok event to check the value, but I don't know how to trigger a click.

I know that I can use EditTextPreference.setOnPreferenceChangeListener() , but I want to know if I can use the OK button click event.

+1
source share
3 answers

Actually, you cannot, as the preference uses the internal AlertDialog.Builder and creates a new dialog every time you click the preference. The next problem is that the dialog builder sets a click listener for you, and if you override them, you can destroy the behavior of the button that the button clicks.

This bothered me, since I wanted the preference to be closed only on a valid input (otherwise, a toast is displayed, and the user must cancel the cancellation if he cannot understand it correctly).

(If you really need a solution to this particular problem), you can find a general solution for checking DialogPreference here and checking EditTextPreference here , which I wrote myself.

+3
source

You can extend EditTextPreference to gain control of the click handler.

 package myPackage; public class CustomEditTextPreference extends EditTextPreference { public CustomEditTextPreference(Context context) { super(context); } public CustomEditTextPreference(Context context, AttributeSet attrs) { super(context, attrs); } public CustomEditTextPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { // add Handler here } super.onClick(dialog, which); } } 

In Xml, instead of <EditTextPreference/> do the following:

 <myPackage.CustomEditTextPreference android:dialogTitle="Registration Key" android:key="challengeKey" android:title="Registration Key" android:summary="Click here to enter the registration key you received by email."/> 
+2
source

Your preference activity does not realize

OnSharedPreferenceChangeListener

You can read a great answer to the question: Update EditPreference

+1
source

Source: https://habr.com/ru/post/887289/


All Articles