对于android中的自定义的布局的dialog,当调用布局中的控件时,用findviewbyid函数发现返回null。
创建自定义界面的对话框的关键代码如下:
//获得对话框自定义布局 LayoutInflater inflater = getLayoutInflater(); final View layout = inflater.inflate(R.layout.devices_maintain, null);
dialog = new AlertDialog.Builder(this); dialog.setTitle("添加设备信息").setView(layout) .setPositiveButton("确定", dialog_PosButton) .setNegativeButton("取消", dialog_NegButton);
dialog_PosButton = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub EditText devname = (EditText)layout.findViewById(R.id.devname); EditText devintroduce = (EditText)layout.findViewById(R.id.devintroduce); EditText phone_num = (EditText)layout.findViewById(R.id.phonenum); Spinner devtype = (Spinner)layout.findViewById(R.id.spinner_devtype); System.out.println("确定"+which+devname.getText().toString());
综上:想要获取自定义布局中的控件必须调用你所定义的View的findViewById方法,且必须指定view,而非默认,不能像获得其他控件一样直接调用findViewById方法。