0

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

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();

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

我该如何实现这一点(对生成的对话框中的微调器选择做出反应AlertDialog.Builder)?

4

2 回答 2

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);
            }
        }                       
    }
   }

您可以在instanceOfyour_root_view 的帮助下控制何时在 R.layout.my_dialog 上,在我的示例中它是一个 RelativeLayout

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

    <Spinner ... />

    <TextView ... />

 </RelativeLayout>

参考

于 2013-04-28T21:27:55.653 回答
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
}
于 2013-05-01T11:27:11.137 回答