有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从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,
                安卓.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(安卓.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) 个答案

  1. # 1 楼答案

    由于您似乎已经在一个单独的类中定义了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()内完成