Choletski
Choletski

Reputation: 7535

Android Dialog customized OnClickListener

I have a generic class witch makes a simple dialog popup:

public class GenericDialogPopUp {

    public static void genericCreatePopUp(Context context) {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Title");
    builder.setMessage("message body");

    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // do if ok is pressed
        }
    });

    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
                // do if cancel is pressed
        }
    });

    builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.show();
    }
}

and I need to call this method from within Fragment/Activity:

GenericDialogPopUp.genericCreatePopUp(getActivity()); / GenericDialogPopUp.genericCreatePopUp(SomeActivity.this);

the problem is that I 'd like to create a kind of listener to know if ok button from dialog was pressed, then do the stuff in this(where I'm calling dialog) class, like:

  if(ok_bt)

     private void doPositive(){                //code            }

   else   

     private void doNegative(){                //code            }

Upvotes: 1

Views: 590

Answers (1)

Prasad
Prasad

Reputation: 3562

Your genericCreatePopUp method will as follows

  public static void genericCreatePopUp(Context context, final SimpleListener listener) {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Title");
    builder.setMessage("message body");

    builder.setPositiveButton(okTxt, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            listener.onPosBtnClick();
        }
    });

    builder.setNegativeButton(bt_can, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            listener.onNegBtnClick();
        }
    });

    builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.show();
    }

SimpleListener interface:

  interface SimpleListener {
    void onPosBtnClick();
    void onNegBtnClick();
  }

call this from Fragment/Activity:

genericCreatePopUp(context, new SimpleListener (){

     @Override
     onPosBtnClick(){
         // your code
     }

     @Override
     onNegBtnClick(){
          // your code
     }
});

Upvotes: 3

Related Questions