简体   繁体   English

在DialogFragment的onClick方法中从MainActivity调用方法

[英]Invoking methods from MainActivity within the onClick methods of a DialogFragment

I'm trying to use a DialogFragment to show a Dialog within my MainActivity. 我正在尝试使用DialogFragment在MainActivity中显示一个对话框。 Depending on the user's reaction to the dialog I want to invoke methods defined in my MainActivity.java file (eg onActivityResult , but ideally also customized methods). 根据用户对对话框的反应,我想调用MainActivity.java文件中定义的方法(例如onActivityResult ,但最好还是自定义方法)。

Following a reply by ashishduh on this question, I defined the DialogFragment as follows (in a seperate java file): 在ashishduh对这个问题的答复之后,我将DialogFragment定义如下(在单独的Java文件中):

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

public class YesNoDialog extends DialogFragment {
public static final String ARG_TITLE = "YesNoDialog.Title";
public static final String ARG_MESSAGE = "YesNoDialog.Message";

public YesNoDialog() {}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{   Bundle args = getArguments();
    String title = args.getString(ARG_TITLE);
    String message = args.getString(ARG_MESSAGE);

    return new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
                }
            })
            .create();
}
}

Correspondingly, I try to start it from the MainActivity like this: 相应地,我尝试像这样从MainActivity启动它:

    public void openYesNoDialog (View view) {
    DialogFragment dialog = new YesNoDialog();
    Bundle args = new Bundle();
    args.putString(YesNoDialog.ARG_TITLE, "title");
    args.putString(YesNoDialog.ARG_MESSAGE, "message");
    dialog.setArguments(args);
    dialog.setTargetFragment(this, YES_NO_CALL);
    dialog.show(getSupportFragmentManager(), "tag");
}

where openYesNoDialog is triggered by a button in the activity_main.xml layout file. 其中的openYesNoDialog是由activity_main.xml布局文件中的按钮触发的。

I am facing the problem that setTargetFragment(this, YES_NO_CALL) is not working, since "this" corresponds to my MainActivity, but setTargetFragment is (naturally) expecting a Fragment and no Activity. 我面临的问题是setTargetFragment(this, YES_NO_CALL)无法正常工作,因为“ this”对应于我的MainActivity,但是setTargetFragment(自然地)期望一个Fragment且没有Activity。 The problem is that I do not know what to reference in the first argument instead because apart from the DialogFragment I am trying to build I have made absolutely no use of Fragments in my code. 问题是我不知道在第一个参数中引用什么,因为除了我试图构建的DialogFragment外,我在代码中完全没有使用Fragments。 So I am wondering which of the following strategies you would encourage to fix my issue (not even sure if all of them might possibly work): 因此,我想知道您会鼓励采用以下哪种策略来解决我的问题(甚至不确定它们是否都可能有效):

1.) Use a method similar to setTargetFragment which allows setting a target Activity. 1.)使用类似于setTargetFragment的方法,该方法允许设置目标Activity。 (sort of a "setTargetActivity" method; this solution sounds easiest to me if such a thing exists, but I haven't found anything similar yet). (某种“ setTargetActivity”方法;如果存在这种情况,此解决方案对我来说最简单,但我还没有发现任何类似的东西)。

2.) Write everything in terms of Fragments and have something like a "MainFragment" instead of a MainActivity. 2.)用Fragments编写所有内容,并使用“ MainFragment”代替MainActivity。 I could then easily reference this "MainFragment" as a reasonable target fragment with "this". 然后,我可以轻松地将此“ MainFragment”作为带有“ this”的合理目标片段。

3.) Use a completely different approach (eg not putting the methods in the activity but in an interface both activity and fragment implement, but actually I also want to make use of eg TextViews of the activity inside of the DialogFragment, so I think this might be a problem) 3.)使用完全不同的方法(例如,不将方法放在活动中,而在活动和片段实现中都放在接口中,但是实际上,我也想在DialogFragment内部使用活动的TextViews,所以我认为这是可能是一个问题)

I am very thankful for any help. 非常感谢您的帮助。

One final comment: Note that I am using the v4 support libraries in my imports to support backward compatibility as suggested in the Android tutorials on Dialogs. 最后一条评论:请注意,我在导入中使用v4支持库来支持向后兼容性,如Dialogs上的Android教程中所建议。

This is for example why I needed to use getSupportFragmentManager() instead of getFragmentManager() to make work what is already working right now. 例如,这就是为什么我需要使用getSupportFragmentManager()而不是getFragmentManager()来使当前已经在工作的东西起作用的原因。 So that's the reason for my slight modifications of the code I have been referring to with the hyperlink. 因此,这就是我对超链接所引用的代码进行微小修改的原因。

getTargetFragment and setTargetFragment both we should use for communication between Fragment to Fragment, 我们应使用getTargetFragmentsetTargetFragment进行Fragment与Fragment之间的通信,

For Activity to Fragment communication, you can use 2 ways 对于“ Activity Fragment通信,可以使用两种方法

  1. You can use interface for communication 您可以使用界面进行通讯

  2. You can use Local broadcast 您可以使用本地广播

Interface communication 接口通讯

Create one interface in dialog fragment, 在对话框片段中创建一个接口,

public class YesNoDialog extends DialogFragment {
   public interface OnDialogActionListener {
       public void onClickDialog();
   }

   private OnDialogActionListener mListener;

   @Override
   public void onAttach(Context context) {
       mListener = (OnDialogActionListener) context;
   }

   // Your code

               @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    mListener.onClickDialog();
                }

}

And in Your activity you can implement and override the function, you will get callback in your Activty. 在您的活动中,您可以实现和覆盖功能,您将在Activty中获得回调。

You can simply use interface for the same. 您可以简单地使用接口。 Just define interface in a separate class and declare method as onClickEvent/onSuccess according to you and override it in your activity and perform your task in your activity in the method. 只需在单独的类中定义接口,然后根据您的需要将方法声明为onClickEvent / onSuccess,并在您的活动中覆盖它,并在该方法中的活动中执行您的任务即可。 And call this method from your dialog on yes/no click buttons. 然后从是/否单击按钮的对话框中调用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM