How to select a entry in AlertDialog with single choice checkbox android? - java

I have an alert dialog with a single-choice list and two buttons: an OK button and a cancel button. The code below show how I implemented it.
private final Dialog createListFile(final String[] fileList) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Compare with:");
builder.setSingleChoiceItems(fileList, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(TAG,"The wrong button was tapped: " + fileList[whichButton]);
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
return builder.create();
}
My goal is to obtain the name of the selected radio button when the OK button is tapped. I tried to save the string in a variable, but inside an inner class it is possible to access only final variables. Is there a way to avoid using a final variable to store the selected radio button?

Using a final variable obviously won't work (since it can only be assigned once, at declaration time). So-called "global" variables are usually a code smell (especially when they become part of an Activity class, which is usually where AlertDialogs are created).
The cleaner solution is to cast the DialogInterface object to an AlertDialog and then call getListView().getCheckedItemPosition(). Like this:
new AlertDialog.Builder(this)
.setSingleChoiceItems(items, 0, null)
.setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful withe the position of the selected radio button
}
})
.show();

This has been answered just fine, but I keep finding this answer from Google and I wanted to share a non-anonymous class solution. I prefer reusable classes myself and may be helpful to others.
In this example, I'm using a DialogFragment implementation and retrieving a value via a callback method.
The callback method to get values from a Dialog can be done by creating a public interface
public interface OnDialogSelectorListener {
public void onSelectedOption(int selectedIndex);
}
Also the DialogFragment implements DialogInterface.OnClickListener which means you can register the class you've implemented as the OnClickListener for the DialogFragment that is being created.
For example
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle(R.string.select);
builder.setSingleChoiceItems(mResourceArray, mSelectedIndex, this);
builder.setPositiveButton(R.string.ok, this);
builder.setNegativeButton(R.string.cancel, this);
return builder.create();
}
The line
builder.setSingleChoiceItems(mResourceArray, mSelectedIndex, this);
Creates a choice dialog with the options from a resource array stored in mResourceArray. This also preselects an option index from what is stored in mSelectedIndex and finally it sets this itself as the OnClickListener. (See full code at the end if this paragraph is a tad confusing)
Now, the OnClick method is where you grab the value that comes from the dialog
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Dialog.BUTTON_NEGATIVE: // Cancel button selected, do nothing
dialog.cancel();
break;
case Dialog.BUTTON_POSITIVE: // OK button selected, send the data back
dialog.dismiss();
// message selected value to registered callbacks with the
// selected value.
mDialogSelectorCallback.onSelectedOption(mSelectedIndex);
break;
default: // choice item selected
// store the new selected value in the static variable
mSelectedIndex = which;
break;
}
}
What happens here is when an item is selected, it's stored in a variable. If the user clicks the Cancel button, no update is sent back and nothing changes. If the user clicks the OK button, it returns the value to the Activity that created it via the callback created.
As an example, here is how you would create the dialog from a FragmentActivity.
final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array, preSelectedValue);
sd.show(getSupportFragmentManager(), TAG);
Here, the resource array _R.array.selector_array_ is an array of strings to show in the dialog and preSelectedValue is the index to select on open.
Finally, your FragmentActivity will implement OnDialogSelectorListener and will receive the callback message.
public class MyActivity extends FragmentActivity implements OnDialogSelectorListener {
// ....
public void onSelectedOption(int selectedIndex) {
// do something with the newly selected index
}
}
I hope this is helpful to someone, as it took me MANY attempts to understand it. A full implementation of this type of DialogFragment with a callback is here.
public class SelectorDialog extends DialogFragment implements OnClickListener {
static final String TAG = "SelectorDialog";
static int mResourceArray;
static int mSelectedIndex;
static OnDialogSelectorListener mDialogSelectorCallback;
public interface OnDialogSelectorListener {
public void onSelectedOption(int dialogId);
}
public static DialogSelectorDialog newInstance(int res, int selected) {
final DialogSelectorDialog dialog = new DialogSelectorDialog();
mResourceArray = res;
mSelectedIndex = selected;
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mDialogSelectorCallback = (OnDialogSelectorListener)activity;
} catch (final ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnDialogSelectorListener");
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle(R.string.select);
builder.setSingleChoiceItems(mResourceArray, mSelectedIndex, this);
builder.setPositiveButton(R.string.ok, this);
builder.setNegativeButton(R.string.cancel, this);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case Dialog.BUTTON_NEGATIVE:
dialog.cancel();
break;
case Dialog.BUTTON_POSITIVE:
dialog.dismiss();
// message selected value to registered calbacks
mDialogSelectorCallback.onSelectedOption(mSelectedIndex);
break;
default: // choice selected click
mSelectedIndex = which;
break;
}
}
}
Question from a comment How to call this from a Fragment instead of an Activity.
First make a few changes to the DialogFragment.
Remove the onAttach event since that's not the easiest way in this scenario.
Add a new method to add a reference to the callback
public void setDialogSelectorListener (OnDialogSelectorListener listener) {
this.mListener = listener;
}
Implement the listener in your Fragment
public class MyFragment extends Fragment implements SelectorDialog.OnDialogSelectorListener {
// ....
public void onSelectedOption(int selectedIndex) {
// do something with the newly selected index
}
}
Now create a new instance and pass in a reference to the Fragment to use it.
final SelectorDialog sd = SelectorDialog.newInstance(R.array.selector_array, preSelectedValue);
// this is a reference to MyFragment
sd.setDialogSelectorListener(this);
// mActivity is just a reference to the activity attached to MyFragment
sd.show(this.mActivity.getSupportFragmentManager(), TAG);

final CharSequence[] choice = {"Choose from Gallery","Capture a photo"};
int from; //This must be declared as global !
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Upload Photo");
alert.setSingleChoiceItems(choice, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (choice[which] == "Choose from Gallery") {
from = 1;
} else if (choice[which] == "Capture a photo") {
from = 2;
}
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (from == 0) {
Toast.makeText(activity, "Select One Choice",
Toast.LENGTH_SHORT).show();
} else if (from == 1) {
// Your Code
} else if (from == 2) {
// Your Code
}
}
});
alert.show();

As others have pointed out, implementation 'com.google.android.material:material:1.0.0' it is more simply
Refere this material guide for more. https://material.io/develop/android/docs/getting-started/
CharSequence[] choices = {"Choice1", "Choice2", "Choice3"};
boolean[] choicesInitial = {false, true, false};
AlertDialog.Builder alertDialogBuilder = new MaterialAlertDialogBuilder(getContext())
.setTitle(title)
.setPositiveButton("Accept", null)
.setNeutralButton("Cancel", null)
.setMultiChoiceItems(choices, choicesInitial, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
}
});
alertDialogBuilder.show();

Try this.
final String[] fonts = {"Small", "Medium", "Large", "Huge"};
AlertDialog.Builder builder = new AlertDialog.Builder(TopicDetails.this);
builder.setTitle("Select a text size");
builder.setItems(fonts, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if ("Small".equals(fonts[which])) {
Toast.makeText(MainActivity.this,"you nailed it", Toast.LENGTH_SHORT).show();
}
else if ("Medium".equals(fonts[which])) {
Toast.makeText(MainActivity.this,"you cracked it", Toast.LENGTH_SHORT).show();
}
else if ("Large".equals(fonts[which])){
Toast.makeText(MainActivity.this,"you hacked it", Toast.LENGTH_SHORT).show();
}
else if ("Huge".equals(fonts[which])){
Toast.makeText(MainActivity.this,"you digged it", Toast.LENGTH_SHORT).show();
}
// the user clicked on colors[which]
}
});
builder.show();

Related

Visual customization of a dialog button

I am using a dialog in my app that pops up and interacts with the user. I haven't worked with dialogs before, so i know next to nothing about styling them. This is the code:
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
Can we style the "Save" button to display red text?
You can get the Button and then change it's text color. Something along the following lines should work,
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(Color.parseColor("#FF0B8B42"));
}
You can use AlertDialog as Chrisvin Jem suggested in his answer but I would like to offer another solution:
You can just create a custom dialog class in order to give your dialog a custom layout, control everything in a separate class - I find it cleaner and more organized.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog
Why I recommend using this and not AlertDialog.Builder :
You can build your layout in a faster way with custom dialog.
No need to write a lot of code just to add views when you can have a custom layout.
It's easier (or so I believe) for you to see myCoolDialog.show(); rather than 50 lines of code or more in a single method.
Do you need to change anything regarding your dialog look and code? good, go to your separate class and change it instead of adding 20 more code lines to your activity.
Chrisvin Jem gave the extact answer to your question however if you want more control over your design you can the this code
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.yourview);
RelativeLayout submit = dialog.findViewById(R.id.submit);
final EditText edittext = dialog.findViewById(R.id.edittext);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(context, getString(R.string.thanks), Toast.LENGTH_SHORT).show();
}
});
dialog.show();

Programmatically accessing AlertDialog PositiveButton

I am using an AlertDialog to ask the user to enter a numerical value on a long press of a view. This uses the Android soft-keyboard. For a better user experience I would like the keyboard "Enter" button to programmatically click the Alert Dialog's positive button and run it's onClick. This is really awkward because I can't find any reference to the positive button in the dialog objects. Code to illustrate:
customStakeView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Custom Stake");
customStakeSet = false;
// Set up the input
final EditText input = new EditText(context);
input.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
// Specify the type of input expected;
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(keyEvent.getAction() == KeyEvent.ACTION_DOWN){
if(!input.getText().toString().equals("")){
switch (keyCode){
case KeyEvent.KEYCODE_ENTER:
//Positive Button Outcome
}
}
}
return false;
}
});
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String newStake = input.getText().toString();
if (!newStake.equals("")) {
newStake = newStake.replaceAll("[^\\d.]", ""); //strip down to currency format
customStake = new Stake(newStake);
customStakeSet = true;
deselectAll();
selectCustomStake();
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
});
I've caught the KeyEvent, and if this was a button added via XML, or even defined with a variable, I would easily be able to do
button.performClick();
but AlertDialog doesn't seem to have such a reference
EDIT:
From documentation, use getButton(whichButton)
Gets one of the buttons used in the dialog. Returns null if the specified button does not exist or the dialog has not yet been fully created (for example, via show() or create()).
whichButton can be BUTTON_POSITIVE or any other button you have specified.
Below is a screenshot of it.
You aren't catching AlertDialog returned by .create() method. getButton() is not available to builder, but to AlertDialog object.
builder.setPositiveButton(...);
// you're missing this
final AlertDialog alertDialog = builder.create();
// then, use it like this
alertDialog.getButton(DialogInterface.Button_POSITIVE).performClick();

AlertDialog return boolean value

I am trying to include an AlertDialog builder within a method that prompts for a pin code and when the positive button is pressed, checks it against a database value and returns a true or false value to the method caller.
For example: Adding/editing/deleting a user task requires a pin code. I don't want to generate a different AlertDialog for all three (and more) of these actions. I want to wrap the following code within a TaskService class that I can call from any activity, and react based on the result from within that activity.
So TaskService.java would have:
public boolean isCorrectPin(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
final EditText editText = new EditText(context);
builder.setView(editText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString()) == getPinCode(){
//return true
}
}
});
builder.show();
}
and OpenTaskAdapter.java would have:
public void onBindViewHolder(ViewHolder holder, int position){
holder.btnMarkAsComplete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//complete task
}
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (service.isCorrectPin(v) {
//delete task
}
}
});
It's important to note that these two button listeners could be in totally different activities.
You can create your own method to generate dialog with listener:
public void isCorrectPin(Context context, String title, String message, String btnPositive, final DialogSingleButtonListener dialogSingleButtonListener) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton(btnPositive, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (editText.getText().toString() == getPinCode()){
dialogSingleButtonListener.onButtonClicked(dialog);
}
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
And the listener class:
public interface DialogSingleButtonListener {
public abstract void onButtonClicked(DialogInterface dialog);
}
And use it like:
service.isCorrectPin(context, title, message, btnPositive
new DialogSingleButtonListener() {
#Override
public void onButtonClicked(DialogInterface dialog) {
//code here is only called if they entered a correct pin.
}
}
);
A dialog can't "return" a value in the way that it looks like you're expecting. A dialog can make changes to some other object, but you can't have a bit of code block on it and wait for the user to finish interacting with it.
Instead, you'll need to set up listeners for when the prompt dialog is dismissed or buttons or clicked, or whatever other event signals that you have what you need from it. Those listeners can then read the data gathered and set by the dialog.
this is how i'm doing :
public Boolean showAlert(String message)
{
action = false;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(HAActivity.this);
// Setting Dialog Title
alertDialog.setTitle(getString(R.string.app_name));
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
action = true;
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
action = false;
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
return action;
}
and calling function like this :
//activity in which you create function
if (Activity.showAlert("Do you really want to delete ??"))
{
//delete it anyway.
}

AlertDialog Extern - all fine but not returning the value as I wish

I'm trying to make a extern class for AlertDialog. I want to have an universal class to use it quickly.I know the code isn't difficult at all, but there are anyhow many rows to write (or copy) and if I would find a mistake I maybe had to change many code...
I've everything but one thing I don't get.
So it works but returning the correct onClick doesn't work.
I've also tried to make an while loop before returning, but then the app is hanging....
Has somebody any idea?
public class RalaAlertDialog{
private static AlertDialog.Builder alertDialog;
private static long onClick=RalaInterfaceDefault.FehlerSpezialZahl;
//neutralButton
public static long AlertDialogNeutral(Context class_this, String mssg, String ntrlBttnTxt, boolean dismissable, String title){
onClick=RalaInterfaceDefault.FehlerSpezialZahl; //default error number
alertDialog=new AlertDialog.Builder(class_this);
if(mssg.equals("")){
mssg="DEFAULT-TEXT";
}
if(title.equals("")){
title="DEFAULT-TITLE";
}
if(ntrlBttnTxt.equalsIgnoreCase("")){
System.out.println("No values set - default in use.");
ntrlBttnTxt="OK";
}
alertDialog.setMessage(mssg)
.setCancelable(dismissable);
alertDialog.setTitle(title);
alertDialog.setPositiveButton(ntrlBttnTxt,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
onClick=0;
dialog.dismiss();
}
}
);
AlertDialog a=alertDialog.create();
a.show();
//wait until button is click before continuing
return onClick;
}
public static AlertDialog getAlertDialog(Context ctx, String title, String message, String posButton, boolean dismissable, final DialogInterface.OnClickListener ocl) {
AlertDialog.Builder builder =new AlertDialog.Builder(ctx);
builder.setTitle(title)
.setMessage(message)
.setCancelable(dismissable)
.setPositiveButton(posButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.dismiss();
if(ocl!=null) ocl.onClick(dialog, id);
}
});
AlertDialog dialog = builder.create();
return dialog;
}
Use it like this :
AlertDialog dialog = getAlertDialog(this,"Hello","World","OK",false,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i("DIALOG","OK Clicked");
}
});
dialog.show();
Of course you need only one OnClickListener, but I like it better that way.

Custom AlertDialog.Builder class in android won't show

I'm currently writing a program that will use the Geocoder to search for possible GeoPoints of a city search. I then take the geopoints and add it to a map as overlays, the user can then click the overlay, and an alert dialog will pop up to ask if he/she is sure that this is the right one.
I couldn't figure out a way to get the alert dialog to work like swing where after the user clicks yes or no, I can retrieve the answer. So I extended the AlertDialog.Builder class like so, which also happens to be a Dialog.OnClicklistener
public class MyAlertDialog extends AlertDialog.Builder implements DialogInterface.OnClickListener{
final static int positiveMessage = 1;
final static int negativeMessage = 0;
final static int neutralMessage = -1;
private int myMessage;
public MyAlertDialog(Context activity) {
super(activity);
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == dialog.BUTTON_POSITIVE){
myMessage = positiveMessage;
}
else if(which == dialog.BUTTON_NEGATIVE){
myMessage = negativeMessage;
}
else{
myMessage = neutralMessage;
}
}
public int getMessage() {
return myMessage;
}
and I implement it like so
protected boolean onTap(int index) {
OverlayItem item = overlays.get(index);
MyAlertDialog dialog = new MyAlertDialog(ctx);
dialog.setTitle(item.getTitle());
dialog.setMessage("Is this the " + item.getTitle()
+ " you're looking for?");
dialog.setPositiveButton("Yes",null);
dialog.setNegativeButton("Cancel", null);
dialog.show();
if(dialog.getMessage()== MyAlertDialog.positiveMessage){
//do some stuff
But for some reason the dialog wont show until after the method has returned, so it never does the stuff. Anyone have any ideas? Oh and ctx is a reference to my mapActivity
This is because the dialog.show(); method does not wait for the user to interact with the Dialog before returning. It does exactly what the name would suggest, and nothing more; it shows the Dialog, and then returns. So, that means that your myMessage field will always be null and this condition will never be true:
if(dialog.getMessage()== MyAlertDialog.positiveMessage){
What you should do instead is pass in OnClickListener for both your positive and negative button, and do whatever you need to in the respective OnClickListener. You won't even need to make a subclass of AlertDialog.Builder, because there won't be any benefit to doing that. Here's how that looks:
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
// Do some positive stuff here!
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
// Do some negative stuff here!
}
});

Categories

Resources