对于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方法。
本文介绍了解决Android自定义Dialog中控件获取返回null的问题。通过LayoutInflater加载自定义布局,并正确使用findViewById方法来获取控件引用。文章强调了在自定义视图中必须指定view来查找控件。
1093

被折叠的 条评论
为什么被折叠?



