Skip to content Skip to sidebar Skip to footer

Get Event On Dialog( Ok ,cancel) Button Pressed(android)

In my Android application I am displaying the dialogbox which contains edittext. This dialogbox is displayed using PreferenceCategory.My xml file looks like

Solution 1:

If I get your question correctly, you want to handle the "Ok" and "Cancel" event and then perform some action based on the response.

// This is using code:
AlertDialog.Builderalert=newAlertDialog.Builder(this);
alert.setTitle("TITLE HERE");
alert.setMessage("MESSAGE");

alert.setPositiveButton("Ok", newDialogInterface.OnClickListener() {
    publicvoidonClick(DialogInterface dialog, int whichButton) {
     //Do something here where "ok" clicked
    }
});
alert.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
    publicvoidonClick(DialogInterface dialog, int whichButton) {
    //So sth here when "cancel" clicked.
    }
});
alert.show();

Solution 2:

You will need to create your custom edit text preference as follows.

publicclassMyEditTextPreferenceextendsEditTextPreference {

    publicMyEditTextPreference(Context context) {
        super(context);
    }
    publicMyEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    publicMyEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @OverridepublicvoidonClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
        // Put your logic here for Ok button pressbreak;

        case DialogInterface.BUTTON_NEGATIVE:
        // Put your logic here for Cancel button pressbreak;      
        }
        super.onClick(dialog, which);
    }
}

Then use it in xml file as follows:

<com.package.MyEditTextPreference
android:dialogTitle="@string/security_setting_button"android:key="set_password_preference"android:summary="@string/set_password_summary"android:title="@string/security_setting_button"android:inputType="number"android:icon="@drawable/lock"
 />

where com.package should be replaced by the actual package in your project where you create MyEditTextPreference

Solution 3:

DialogInterface.OnClickListenerdialogClickListener=newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
    switch (which){
    case DialogInterface.BUTTON_POSITIVE:
        //Yes button clickedbreak;

    case DialogInterface.BUTTON_NEGATIVE:
        //No button clickedbreak;
    }
   }


 };

   AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
   builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
    .setNegativeButton("No", dialogClickListener).show();

Post a Comment for "Get Event On Dialog( Ok ,cancel) Button Pressed(android)"