findViewById()调用组件返回null,getText()无法执行,程序未报错
下面的程序是创建一个对话框,有两个EditText组件,用于填写RSS名称和RSS地址,点击按钮获取输入的数据。
第十二行、十三行代码要注意。
EditText nameText = (EditText)view.findViewById(R.id.rss_name_edit); EditText addressText = (EditText)view.findViewById(R.id.rss_address_edit);
这一句代码,不能直接用
EditText nameText = (EditText)findViewById(R.id.rss_name_edit);这样nameText只能得到null值。接下来的getText()自然执行不下去了。而且程序不会报错。
因为findViewId是默认在当前activity的默认布局文件寻找该组件的。
应当将该组件所在的布局文件定义出来,再通过该布局文件获取组件。
如下:
LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.add_rss, null);
EditText nameText = (EditText)view.findViewById(R.id.rss_name_edit);
源程序如下:
private Dialog builderDialog1(Context context) { LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.add_rss, null); AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setIcon(R.drawable.add); dialog.setTitle(R.string.dialog_input_rss_name); dialog.setView(view); dialog.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { EditText nameText = (EditText)view.findViewById(R.id.rss_name_edit); EditText addressText = (EditText)view.findViewById(R.id.rss_address_edit); String rss_name = nameText.getText().toString(); String rss_url = addressText.getText().toString(); if(rss_name.equals("")) { Toast.makeText(ActivityRssList.this, ":( RSS名称不能为空!", Toast.LENGTH_SHORT).show(); } else if(!URLUtil.isNetworkUrl(rss_url)) { Toast.makeText(ActivityRssList.this, ":( RSS地址格式不正确!", Toast.LENGTH_SHORT).show(); } else { if(dbAdapter.saveRSS(rss_url, rss_name, type_id)) { Toast.makeText(ActivityRssList.this, "添加成功:)!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ActivityRssList.this, "对不起,添加失败了:( 请重新添加!", Toast.LENGTH_SHORT).show(); } } showRSSList(); //刷新rss列表 } }); dialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); return dialog.create(); }