从Android中的AlertDialog返回信息

时间:2015-03-22 16:10:11

标签: java android callback android-alertdialog

我创建了以下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。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

由于您似乎已在单独的类中定义了AlertDialog,因此您无法直接访问Activity中调用它的方法。

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

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()内完成。