how to call the ok button in the EditTextPreferenc

2020-02-02 01:58发布

问题:

I have an EditTextPreference in the PreferenceActivity. When user click the EditTextPreference will show a dialog. In the dialog, user can input a value, and the dialog has "OK" and "Cancel" buttons. I want to call the click event of ok button to check the value, but I do not know how to call the click even.

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

回答1:

Actually you can't since the preference is using an internal AlertDialog.Builder and creates a new dialog every time you click the preference. The next problem is that the dialog builder sets the click listener for you and if you override them you might destroy the close behavior of the button click.

This bothered me since I wanted a preference which only closes on valid input (otherwise a toast is shown and user should press cancel if he can't get it right).

(If you really need a solution for exactly this problem) You can find general solution of a validating DialogPreference here and a validating EditTextPreference here which I wrote myself.



回答2:

You can extend EditTextPreference to get control over 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 the Xml instead of <EditTextPreference/> reference it like this:

<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."/>


回答3:

Your preference activity doesn't appear to be implementing a

OnSharedPreferenceChangeListener

You may want to read over the excellent answer to the question: Updating EditPreference