如何在AlertDialog.Builder生成的对话框中对微调器项目选择做出反应?

时间:2013-04-28 20:19:46

标签: android android-spinner android-alertdialog

在我的应用程序中,我显示一个对话框,其中包含以下代码:

final AlertDialog.Builder builder = new AlertDialog.Builder(
        getActivity());
final View myDialogForm = getActivity().getLayoutInflater()
        .inflate(R.layout.my_dialog, null);

builder.setTitle(R.string.addCompanyDialogTitle)
    .setView(myDialogForm)
    .create()
    .show();

它包含SpinnerTextView。当用户在微调器中选择某些内容时,必须更新文本视图。

如何实现此功能(对AlertDialog.Builder生成的对话框中的微调器选择做出反应)?

2 个答案:

答案 0 :(得分:1)

您可以使用递归函数迭代通过对话框的视图,例如:

    Dialog di = builder.setTitle(R.string.addCompanyDialogTitle).setView(myDialogForm).create();
    updateMessage(di.getWindow().getDecorView());
    di.show();
    //...
    private void updateMessage(View parent){
     if(parent instanceof ViewGroup){
        ViewGroup vg = (ViewGroup) parent;
        for(int i=0; i < vg.getChildCount();i++){
            View v = vg.getChildAt(i); 
            if(v instanceof RelativeLayout){
                RelativeLayout rl = (RelativeLayout) v;
                TextView tv = (TextView) rl.getChildAt(1);
                Spinner sp = (Spinner) rl.getChildAt(0);
                sp.setOnItemSelectedListener( 
                                        //..
                                        tv.setText(sp_value); 
                                        //..
                                    )
                break;
            } else {
                updateMessage(v);
            }
        }                       
    }
   }

您可以在instanceOf your_root_view的帮助下控制何时使用R.layout.my_dialog,在我的示例中,它是RelativeLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android">

    <Spinner ... />

    <TextView ... />

 </RelativeLayout>

Reference

答案 1 :(得分:0)

我用这种方式解决了问题:

1)修改上面的代码,如下所示:

final AlertDialog.Builder builder = new AlertDialog.Builder(
        getActivity());
final View myDialogForm = getActivity().getLayoutInflater()
        .inflate(R.layout.my_dialog, null);

final Spinner mySpinner = 
    (Spinner) addCompanyDialogForm.findViewById(R.id.spinner_id);

finalOutputSpinner.setOnItemSelectedListener(this);

builder.setTitle(R.string.addCompanyDialogTitle)
    .setView(myDialogForm)
    .create()
    .show();

2)使类实现接口AdapterView.OnItemSelectedListener

3)在该类中实现该接口的方法:

@Override
public void onItemSelected(final AdapterView<?> aParent, final View aView,
        final int aPosition, final long aRowId) {
    // aRowId contains the index of the selected item
}

@Override
public void onNothingSelected(final AdapterView<?> aParent) {
    // Nothing is selected
}