从 Android 中的 AlertDialog 返回信息

Returning information from an AlertDialog in Android

我创建了以下 AlertDialog。在其中,用户从存储在 XML 文件中并使用 Adapter 处理的一系列选项中选择一个项目,然后单击肯定按钮或否定按钮。这是代码:

public void OpenDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        dialog.setTitle("Promotion Options");
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(activity.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(com.zlaporta.chessgame.R.layout.promotion, null);

        dialog.setView(v);
        dialog.setPositiveButton("Choose", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 1) {
                    System.out.println("ok");
                }
            }
        });
        dialog.setNegativeButton("Undo Move", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();

        Spinner spinner = (Spinner) v.findViewById(com.zlaporta.chessgame.R.id.promotionSpin);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, com.zlaporta.chessgame.R.array.option,
                android.R.layout.simple_spinner_item);
        //could be other options here instead of simple_spinner_dropdown_item. Just type simple and see what comes up next time
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

现在,我希望在单击肯定按钮后将有关用户在微调器中的选择的信息传回封闭的 Activity。执行此操作的最佳方法是什么?

由于您似乎在单独的 class 中定义了 AlertDialog,因此您不能 直接 访问 Activity 中定义的方法它被调用的地方。

一种可能的方法是在 Activity 中定义一个 public 方法,如下所示:

public void doSomething(Object spinnerDataObject){

    ....

}

并以这种方式访问​​它:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        // call the Activity's method here and send the selected item.          
        ((MainActivity)activity).doSomething(parent.getItemAtPosition(position));
        dialog.dismiss();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});

这会将选定的 Spinner 数据对象发送到 Activity。无论您想对该对象做什么,都可以在 doSomething().

中完成