Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1050736
  • 博文数量: 403
  • 博客积分: 10272
  • 博客等级: 上将
  • 技术积分: 4407
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:22
文章分类

全部博文(403)

文章存档

2012年(403)

分类: 嵌入式

2012-03-20 19:27:06

今天再做一个程序时,发现我使用findViewById(R.id.edit)获取EditText时总是报空指针错误,我想不可能啊!!

最后从findViewById()下手,才发现原来此方法中的R.id.edit是从当前Activity或者Dialog的主布局文件xml中获取。

比如:我的程序:

ListActivity类中:

。。。。。。。

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.list_view);

}

。。。。。

/**
  * 显示弹出的输入窗口
  * */
 public void showInputDialog(FileBean fileBean) {
  LayoutInflater layoutInflater = getLayoutInflater();
  View layout = layoutInflater.inflate(R.layout.input_dialog,
    (ViewGroup) findViewById(R.id.input_dialog));
  EditText editText = (EditText)layout.findViewById(R.id.input_content);// 获取输入文本框  如果改成EditText editText = (EditText)this.findViewById(R.id.input_content);// 空指针错误
  new AlertDialog.Builder(this)
    .setTitle("重命名文件" + new File(fileBean.getPath()).getName())
    .setView(layout)
    .setPositiveButton("确定", new MyDialogListener(editText))
    .setNegativeButton("取消", new MyDialogListener(editText)).show();
 }

布局文件:

input_dialog.xml



 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:orientation="horizontal" android:id="@+id/input_dialog">
   android:layout_height="50dip" android:textSize="15dip" android:text="@string/rename_file">
   android:layout_width="150dip" android:layout_height="50dip">

list_view.xml



 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:orientation="vertical">
   android:layout_height="wrap_content" android:text="@string/title">
 

   android:layout_width="wrap_content" android:layout_height="wrap_content">
     android:layout_height="40dip" android:text="@string/search"
   android:singleLine="true">

     android:layout_width="40dip" android:layout_height="40dip"
   android:background="@drawable/search">

 

   android:layout_height="wrap_content">
   android:layout_height="wrap_content" android:scrollbarSize="15dip"
  android:fadingEdge="none" android:divider="#222553"
  android:dividerHeight="2dip" android:cacheColorHint="#000000">


原因:因为EditText editText = (EditText)layout.findViewById(R.id.input_content);是从Dialog对话框布局layout中寻找ID为input_content的子元素

   EditText editText = (EditText)this.findViewById(R.id.input_content);// 空指针错误    因为是从this对象即当前ListActivity的布局List_view.xml中寻找ID为input_content的子元素EditText,而我们在List_view.xml布局文件中并无定义此元素故空指针错误 ,并且我们的目的并不是这样。。。。

 

只要理解findViewById就行了。。。。。

阅读(704) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~