实现DialogFragment的回调

时间:2016-11-17 13:40:18

标签: java android android-dialogfragment

从我的Recylerview Adapter,每个项目中都有多个按钮, 我想要的是在点击它们时显示DialogFragment as confirmation,并在点击positiveButton时执行不同的方法/操作。

问题是我不知道如何点击positiveButton时如何实现回调,如何根据每个项目点击的按钮执行不同的方法或操作

e.g.在我的适配器类

@Override
public void onBindViewHolder(final PageOnlineAdapter.TheViewHolder holder, final int position) {

    holder.btn_start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = ConfirmationDialog.newInstance(TITLE,CONTENT); //Initialize DialogFragment with a specific Title and Content
            newFragment.show(((AppCompatActivity)contextView).getSupportFragmentManager(), TAG); 
            /*
                if positiveButton is clicked
                    =>execute method/action here
            */
        }
    );

    holder.btn_stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = ConfirmationDialog.newInstance(TITLE,CONTENT); //Initialize DialogFragment with a specific Title and Content
            newFragment.show(((AppCompatActivity)contextView).getSupportFragmentManager(), TAG); 
            /*
                if positiveButton is clicked
                    =>execute method/action here
            */  
        }
    );

    holder.btn_close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = ConfirmationDialog.newInstance(TITLE,CONTENT); //Initialize DialogFragment with a specific Title and Content
            newFragment.show(((AppCompatActivity)contextView).getSupportFragmentManager(), TAG); 
            /*
                if positiveButton is clicked
                    =>execute method/action here
            */  
        }
    );

    holder.btn_remove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = ConfirmationDialog.newInstance(TITLE,CONTENT); //Initialize DialogFragment with a specific Title and Content
            newFragment.show(((AppCompatActivity)contextView).getSupportFragmentManager(), TAG); 
            /*
                if positiveButton is clicked
                    =>execute method/action here
            */ 
        }
    );
}

这是我的DialogFragment类

public class ConfirmationDialog extends DialogFragment {

    public static ConfirmationDialog newInstance(String title, String description) {
        ConfirmationDialog frag = new ConfirmationDialog();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putString("description", description);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String title = getArguments().getString("title");
        String description = getArguments().getString("description");
        return new AlertDialog.Builder(getActivity())
                //.setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setMessage(description)
                .setPositiveButton("CONTINUE",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                               //How to tell when this positiveButton is clicked
                            }
                        }
                )
                .setNegativeButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //How to tell when this negativeButton is clicked
                            }
                        }
                )
                .create();
    }
}

2 个答案:

答案 0 :(得分:3)

首先,我想感谢Merve Sahin创建Interface的想法。

而不是接受的答案,我最终使用下面的代码。 这使我有一个DialogFragment类,并在许多情况e.g. Calling by Multiple Buttons and response according to what button is clicked中使用它。

首先,您需要import以下内容:

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

对于 AlertDialog ,创建一个类:

public class ConfirmDialog extends DialogFragment {

    public static final String TITLE = "title", CONTENT = "content";
    private OnContinueCancelClick continueCancelClick;

    public static ConfirmDialog newInstance(String title, String content) {
        ConfirmDialog frag = new ConfirmDialog();
        Bundle args = new Bundle();
        args.putString(TITLE, title);
        args.putString(CONTENT, content);
        frag.setArguments(args);
        return frag;
    }

    public void setOnContinueCancelClick(OnContinueCancelClick continueCancelClick) {
        this.continueCancelClick = continueCancelClick;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String title = getArguments().getString(TITLE);
        String content = getArguments().getString(CONTENT);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title).setMessage(content)
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if(continueCancelClick != null)
                            continueCancelClick.onCancelClicked();
                    }
                })
                .setPositiveButton("CONTINUE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if(continueCancelClick != null)
                            continueCancelClick.onContinueClicked();
                    }
                });
        Dialog dialog = builder.create();
        return dialog;

    }

    //Declare an Interface
    public interface OnContinueCancelClick{
        void onContinueClicked();
        void onCancelClicked();
    }
}

当显示对话框并且您需要点击按钮时,请说明我的情况:

holder.btn_start.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        /** Start the Dialog Here **/

            ConfirmDialog confirmDialog = ConfirmDialog.newInstance("Titile of Dialog","Content or Description of Dialog"); //Setup Dialog
            confirmDialog.show(((AppCompatActivity)contextView).getSupportFragmentManager(), "confirmDialog"); //Show the Dialog
            confirmDialog.setOnContinueCancelClick(new ConfirmDialog.OnContinueCancelClick(){ //listen on Clicked Button
                    @Override
                    public void onContinueClicked() {
                        //Do some operation or call some functions when Continue button is Clicked
                    }
                    @Override
                    public void onCancelClicked() {
                        //Do Nothing or Do some operation or call some functions when Cancel button is Clicked
                    }
                });

        /**  END **/
    }
);

您可以使用自定义视图布局

执行相同操作
public class ConfirmDialog extends DialogFragment {

    private Button btnCancel, btnContinue;

    public static final String TITLE = "title", CONTENT = "content";
    private OnContinueCancelClick continueCancelClick;

    public static ConfirmDialog newInstance(String title, String content) {
        ConfirmDialog frag = new ConfirmDialog();
        Bundle args = new Bundle();
        args.putString(TITLE, title);
        args.putString(CONTENT, content);
        frag.setArguments(args);
        return frag;
    }

    public void setOnContinueCancelClick(OnContinueCancelClick continueCancelClick) {
        this.continueCancelClick = continueCancelClick;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_custom_layout, container);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //Some initialization or condition here...
        btnCancel = (Button)view.findViewById(R.id.btn_cancel); //Intialize your Cancel Button
        btnContinue = (Button)view.findViewById(R.id.btn_continue); //Intialize your Continue Button

        getDialog().setTitle(getArguments().getString(TITLE)); //Set the Title

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(continueCancelClick != null)
                    continueCancelClick.onCancelClicked(); //Return this
                dismiss(); //Close the Dialog when Done
            }
        });

        btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(continueCancelClick != null)
                    continueCancelClick.onContinueClicked(); //Return this
                dismiss(); //Close the Dialog when Done
            }
        });
    }

    public interface OnContinueCancelClick{
        void onContinueClicked();
        void onCancelClicked();
    }
}

这可以帮助其他人,所以我在使用界面的帮助下发布我的解决方案。

QuestionNepster回答也帮助我实现了很多目标。

希望这能帮到你们。

答案 1 :(得分:-1)

一个选项是创建一个接口,该接口将由Adapter实现并在创建时传递给对话框。然后,对话框可以在单击肯定时调用某个方法,而在单击否定时调用另一个方法:

public interface DialogCallback{

    void clickedPositiveStart();
    void clickedPositiveStop();
    void clickedNegativeStart();
    void clickedNegativeStop();
}




public class MyAdapter extends Adapter implements DialogCallback, View.OnClickListener{

   @Override
   protected void onClick(View view){
       DialogFragment newFragment =  null;
       String action;

       if(view.getId() == R.id.your_start_button){ 
           action = "start";
       }else if(view.getId() == R.id.your_stop_button){
           action = "stop";    
       }else if(..){
           ....
       }else{
           return;
       }

       newFragment = ConfirmationDialog.newInstance(TITLE,CONTENT, this, action);
       newFragment.show(((AppCompatActivity)contextView).getSupportFragmentManager(), TAG); 
   }

   @Override
   public void clickedPositiveStart(){
        // do something when positive is clicked
   }

   @Override
   public void clickedPositiveStop(){
        // do something when positive is clicked
   }

   @Override
   public void clickedNegativeStart(){
        // do something when negative is clicked
   }

   @Override
   public void clickedNegativeStop(){
        // do something when negative is clicked
   }

}


public ConfirmationDialog extends Dialogfragment{

    private DialogCallback callback;
    private String action;

    public static ConfirmationDialog newInstance(String title, String description, DialogCallback callback, String action) {
        this.callback = callback;
        this.action = action;
        ...
    }


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    String description = getArguments().getString("description");
    return new AlertDialog.Builder(getActivity())
            //.setIcon(R.drawable.alert_dialog_icon)
            .setTitle(title)
            .setMessage(description)
            .setPositiveButton("CONTINUE",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                           if(action.equals("start"){
                              callback.clickedPositiveStart();
                           } else if(action.equals("stop"){
                              callback.clickedPositiveStop();
                           }
                        }
                    }
            )
            .setNegativeButton("CANCEL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                           if(action.equals("start"){
                              callback.clickedNegativeStart();
                           } else if(action.equals("stop"){
                              callback.clickedNegativeStop();
                           }
                        }
                    }
            )
            .create();
     }
 }

}