用户从微调器中选择项目后如何关闭对话框?

时间:2017-12-10 16:16:07

标签: android dialog spinner android-spinner android-dialog

我有一个带微调器的对话框。目前,对话框和微调器工作正常。但是,在我选择一个项目后,微调器并没有关闭。我需要它关闭并在选择项目后返回活动。感谢。

这是我对话框的代码。

    String[] s = {"A", "B", "C", "D", "E", "F" };

        final ArrayAdapter<String> adp = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_spinner_item, s);

        final Spinner sp = new Spinner(getActivity());
        //sp.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        sp.setAdapter(adp);

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                String selectedItem = parent.getItemAtPosition(position).toString();
                Log.d("selectedItem:", selectedItem);

            } // to close the onItemSelected
            public void onNothingSelected(AdapterView<?> parent)
            {

            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(sp);
        builder.create().show();

2 个答案:

答案 0 :(得分:0)

Spinner上没有方法可以关闭它,当选择了微调器项目时,它会关闭你的微调器,添加到setOnItemSelectedListener

sp.setSelection(int position)

然后只需稍微更改一下AlertDialog构造函数,在用户选择微调器中的项目后放置alert.dismiss();以关闭AlertDialog

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(sp);
    final AlertDialog alert = builder.create();
    alert.show();

答案 1 :(得分:0)

试试这个

    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    final Spinner sp = new Spinner(getActivity());
    sp.setAdapter(adp);

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            String selectedItem = parent.getItemAtPosition(position).toString();
            Log.d("selectedItem:", selectedItem);
            builder.dismiss();

        } // to close the onItemSelected
        public void onNothingSelected(AdapterView<?> parent)
        {

        }
    });

    builder.setView(sp);
    builder.create().show();