将数据从对话框片段返回到调用它的活动

时间:2018-07-03 01:57:32

标签: java android

嘿,stackoverflowers !!!

我想知道将基于Dialog上用户输入的,来自Dialog Fragment的字符串传递给调用该字符串的主活动的最佳方法是什么?

这是我的具体示例,但是它确实很长,因此,如果您不愿意经历它,请不要担心下面的所有内容。

这是我的源代码,我省略了导入内容

public class GroupNameFragment extends AppCompatDialogFragment {

    private EditText edittGroupName;

    public static String GROUP_NAME = "com.example.mashu.walkinggroup.controller - groupName";

    // When the views are inflated, get access to them
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        edittGroupName = Objects.requireNonNull(getView()).findViewById(R.id.edittGroupName);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Get reference to fragment's layout
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.group_name_layout, null);

        // OK button listener
        DialogInterface.OnClickListener listener = (dialog, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                // If OK pressed, create bundle to be accessed in OnDismissListener in MapActivity,
                // which contains the groupName user inputted
                String groupName = edittGroupName.getText().toString();
                Bundle bundle = new Bundle();
                bundle.putString(GROUP_NAME, groupName);
                setArguments(bundle);
            }
        };

        // Build alert dialog
        return new AlertDialog.Builder(getActivity())
                .setTitle("Choose your Group Name!")
                .setView(view)
                .setPositiveButton(android.R.string.ok, listener)
                .create();

    }

    // Extracts groupName from the bundle set up in the onClickListener above
    public static String getGroupName(GroupNameFragment dialog) {
        Bundle bundle = getArguments();
        return bundle.getString(GROUP_NAME);
    }
}

我试图做到的是:首先,我可以访问用户将在其响应中键入的EditText。然后,为“确定”按钮设置“对话框侦听器”,该按钮使用setArguments函数创建一个捆绑包,当用户完成操作时,该捆绑包包含groupName,稍后将在其他活动中使用静态getGroupName函数对其进行访问。这是主要活动中的函数,该函数创建Dialog并设置onDismissListener

private void createGroupNameDialog() {
    // Instantiate Dialog
    // Support Fragment Manager for backwards compatibility
    FragmentManager manager = getSupportFragmentManager();
    GroupNameFragment dialog = new GroupNameFragment();
    dialog.show(manager, "GroupNameDialog");

    // OnDismissListener callback function to be run whenever dialog dismissed.
    dialog.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {

            // Update groupName based on what user inputted and update marker name at origin
            groupName = GroupNameFragment.getGroupName(dialog);
            originMarker.setTitle(groupName);

        }
    });
}

我认为问题出在groupName = GroupNameFragment.getGroupName(dialog)中。我觉得有一种更好的方法可以在这里获取捆绑包,并且使用该函数作为静态文件然后传入GroupNameFragment的特定实例以获取捆绑包似乎很奇怪(那个实例到那时就不会消失了)在“ OnDismiss”中使用?)。另外,应用程序崩溃时调用了第二个createGroupNameDialog,但是如果我注释掉OnDismissListener,它不会崩溃并实际上打开对话框窗口,因此我确定那里的问题,但我不知道为什么它崩溃之前该对话框甚至会打开,因为在用户关闭对话框后会发生OnDismiss。

谢谢!

1 个答案:

答案 0 :(得分:0)

我完成了使用接口和侦听器将变量传递回来的工作。我将向您展示如何处理它(尽管我使用了DialogFragment,但它仍适用于AlertDialogs,在此示例中,我传递了一个整数而不是字符串,但它适用于任何数据类型)。

public class DialogFragmentOtherMedia extends DialogFragment {

    int dialogResult;

    //The interface is important!
    public interface YesNoListener {
        void onYesOtherMedia(int output);

        void onNoOtherMedia(int output);
    }

    //Checking for ClassCastException is nice here.
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof YesNoListener)) {
            throw new ClassCastException(activity.toString() + " must implement     YesNoListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialogResult = 0;

        final String mediaType[] = {getString(R.string.Ringtones),getString(R.string.Music),getString(R.string.Alarms)};


        return new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.Select_Other_Media_Type))
                .setSingleChoiceItems(mediaType, dialogResult, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //Log.d("DialogFragmentOtherMedia.onCreateDialog","Item clicked: " + mediaType[which]);

                        dialogResult = which;
                    }
                })
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Casting the activity to YesNoListener is very important here!  
                        //You'll register the listener in the activity later, by implementing the interface.
                        ((YesNoListener) getActivity()).onYesOtherMedia(dialogResult);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Same thing for your other callbacks.
                        ((YesNoListener) getActivity()).onNoOtherMedia(dialogResult);
                    }
                })
                .create();
    }
}

然后,您只需在您从以下位置调用对话框的活动中实现它即可:

public class AlarmDetailsActivity extends Activity
    DialogFragmentOtherMedia.YesNoListener {

    //All of your activity stuff here...

    @Override
    public void onYesOtherMedia(int result) {
        Log.i("Tag", "onYes Result: " + result);
    }

    @Override
    public void onNoOtherMedia(int result) {
        Log.i("Tag", "onNo Result: " + result);

    }



}

对不起,所有随机字符串和额外的警告对话框。我只想显示我的应用程序中的一些实际工作代码。我试图在重要内容旁边添加评论。希望这会有所帮助!