当前位置: 首页 > 知识库问答 >
问题:

实现DialogFragment的回调

东门焕
2023-03-14

从我的Recylerview Adapter中,每个项目中都有多个按钮,我想要的是在单击对话框时将其显示为确认,并在单击时执行不同的方法/操作肯定按钮

问题是我不知道如何才能或如何才能实现一个回调时肯定按钮被点击,并可以执行不同的方法或操作根据什么按钮是点击每个项目。

例如在我的适配器类上

@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个答案

庄实
2023-03-14

一个选项是创建一个接口,该接口将由适配器实现,并在创建时传递给dialogframe。然后,dialogframe可以在单击正极时调用某个方法,在单击负极时调用另一个方法:

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();
     }
 }

}
斜烈
2023-03-14

首先,我要感谢Merve Sahin提出的创建界面的想法。

我没有使用公认的答案,而是使用下面的代码。这使我有了一类DialogFragment,并在许多情况下使用它,例如,通过多个按钮调用并根据单击的按钮进行响应。

首先,您需要导入以下内容:

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();
    }
}

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

尼泊尔人的这个问题回答也帮了我很多。

希望这对你们有帮助。

 类似资料:
  • 问题内容: 我需要构建一个DialogFragment,它将用户输入从对话框返回到活动。该对话框需要在OnClickListener中调用,当单击列表视图中的元素时会调用该对话框。 DialogFragment的返回值(用户的输入)应在活动的OnClickListener中直接可用。 我尝试通过遵循官方文档来实现此目的:http : //developer.android.com/guide/to

  • 下面是一个简单对话框的示例代码: 下面是一些活动代码: 代码与您所看到的引用大致相同。问题是,一旦您改变了方向,当显示对话框时,它就停止了预期的工作-->由于活动生命周期的原因,活动和对话框都被重新构建,并且对话框现在没有对重新构建的新活动的正确引用。 致以最诚挚的问候

  • 在我开始之前,我读过类似的文章,但它们对我不起作用。 正如我在标题中解释的那样,当我单击肯定按钮(在这种情况下为“确定”)时,我会得到一个NPE。如果有人能指出我做得不正确,那就太好了!下面是我的设置的抽象版本

  • 现在我有:- 1) 1活动,它是从AppCompactActivity扩展而来的主要活动。 2) 1扩展自fragment的类,这是从主活动(1)-ProfileTeacherActivity调用的片段。java 3) 1个从DialogFragment扩展的fragment类,此对话框从fragment(2)-ModalBox调用。java 所以,基本上,这只是一个简单的执行流程。开始时,显示的

  • 本文向大家介绍Mybatis中返回Map的实现,包括了Mybatis中返回Map的实现的使用技巧和注意事项,需要的朋友参考一下 在Mybatis中,我们通常会像下边这样用: 返回一个结果 返回多个结果(其实这个和上边一样,只不过是查询条件的控制而已) 我们只要将上边的resultType改为java.util.HashMap,这会有生成下边这样 上这结果就是说,以User类的属性名为key,属性值

  • 我们在“线性回归的简洁实现”一节中已经了解了使用Gluon实现模型的便利。下面,让我们再次使用Gluon来实现一个softmax回归模型。首先导入所需的包或模块。 %matplotlib inline import d2lzh as d2l from mxnet import gluon, init from mxnet.gluon import loss as gloss, nn 获取和读