How to setOnClickListener() to OK button of an Edi

2019-07-27 08:28发布

问题:

Possible Duplicate:
how to call the ok button in the EditTextPreference

I want to validate the Inputs (enter 6 digits) of an EditTextPreference dialog box.

This is how my (relevant) preferences.xml snippet looks like :

            <!--EditTextPreference-->
            <com.app.preferences.UpdatePincodePreference
                android:key="PIN_CODE_PREFERENCE"
                android:title="@string/pincode_preference_title" 
                android:summary="@string/pincode_preference_summary"
                android:dialogTitle="@string/pincode_preference_dialog_title"
                android:dialogMessage="@string/pincode_preference_dialog_message" 
                android:inputType="number"
            />

How do I test that the user has not entered less or more than 6 digits in the EditText of the preference dialog?

Basically I need to set an onClickListener() on the OK button, but how to I get a hold of the OK button which I did not define. Its the default view of an EditTextPreference, and so is the Cancel button.

The question is exactly the same as "how to call the ok button in the EditTextPreference" but the links provided in the accepted solution are broken now.

回答1:

The author of the solution has moved his project from Google Code to GitHub. You can find the new project at https://github.com/Knickedi/android-toolbox and the links to the two files he was referring to validating DialogPreference and validating EditTextPreference



回答2:

This could be achieved using setOnPreferenceChangeListener()

public UpdatePasswordPreference(Context context, AttributeSet attrs) {


    this.setOnPreferenceChangeListener(new OnPreferenceChangeListener() 
    {   
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) 
        {
            MobicopLogger.d("Preference input changed");
            try 
            {
                if(newValue.toString().length() != 6)
                    return false;
                else
                    return true;
            }
            catch(Exception e)
            {
                return false;
            }
        }

    });


}


回答3:

create a custom layout and apply it to the preference by the following override method :

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);    //To change body of overridden methods use File | Settings | File Templates.
    builder.setView(LayoutInflater.from(ctx).inflate(R.layout.custome_preference_layout,null));
}