在android中的自定义警报对话框中访问控件

时间:2010-06-04 11:32:26

标签: android

显示自定义对话框时显示textView和EditView。如何在对话框中访问这些元素。下面是给出错误的代码。

LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_text_entry)
                .setView(textEntryView)
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                     string = uetd.getText().toString() + ":" + petd.getText().toString(); /////producing error
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();

public class listdemo extends ListActivity {
    /** Called when the activity is first created. */
    private static final int DIALOG_TEXT_ENTRY = 7;
    EditText uetd;
    EditText petd;
    SharedPreferences.Editor editor;
    String string;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));

        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
     uetd=(EditText)findViewById(R.id.username_edit);
      petd=(EditText)findViewById(R.id.password_edit);
lv.setOnItemClickListener(new OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

    showDialog(DIALOG_TEXT_ENTRY);
}
        });
}
}

2 个答案:

答案 0 :(得分:3)

而不是立即返回对话框返回新的AlertDialog.builder ....等等......你应该通过创建一个类变量来保存对话框的实例

AlertDialog dialog;

然后,您可以在对话框的回调中轻松访问对话框的视图:

dialog.findViewById(R.id.username_edit);

你必须这样做,因为在创建回调时,它是在内存中构建一个新类的方式,所以当你直接调用findViewById()时它找不到活动

答案 1 :(得分:0)

试试这段代码

 uetd=(EditText) textEntryView.findViewById(R.id.username_edit);

在代码中跟随行后

final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);