现在的位置: 首页 > 综合 > 正文

Android 自定义控件布局 NullPointerException findViewById

2017年12月01日 ⁄ 综合 ⁄ 共 818字 ⁄ 字号 评论关闭

今天被android中的NullPointerException折磨的没脾气了

翻来覆去的看代码觉得很简单的几句话,怎么可能有这种空指针错呢

没有办法只得向高人求助

多亏Long,及时的把我从这种低级错误中点醒

在用LayoutInflater中组合自定义的布局时

我仍然以默认的main.xml文件定义具体的空间

而置自定义的View于不顾,自然在运行时,在默认的布局中找不到我定义的控件

这个错误实在是太低级了

写在这里作为提醒吧!

贴上代码:

 AlertDialog.Builder builder=new AlertDialog.Builder(this);
  LayoutInflater inflater=LayoutInflater.from(this);
  View view=inflater.inflate(R.layout.passworddialog, null);
  final EditText et_username=(EditText)view.findViewById(R.id.username);
  final EditText et_password=(EditText)view.findViewById(R.id.password);
   Button btn_ok=(Button) view.findViewById(R.id.ok);
  Button btn_cancel=(Button)view.findViewById(R.id.cancel);
  //Button btn_ok=(Button) findViewById(R.id.ok);
  //Button btn_cancel=(Button)findViewById(R.id.cancel);
  //注意哦,加View和不加View可是有很大的区别的哦!
  //不加view表明从默认的main.xml文件中读取,而加上则指定从view所代表的那个xml文件中读取

抱歉!评论已关闭.