Android View系列代码问题(一)

来源:互联网 发布:淘宝凳子 编辑:程序博客网 时间:2024/06/01 10:54

findViewById()函数问题
findViewById()函数,以java代码绑定Xml文件,默认是从

protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     }

这个绑定的view中来获取Id,所以当绑定不是此View或者非此View的一级控件,会出现java.lang.NullPointerException
空指针异常的错误。
解决办法
方法一:
将绑定的原view修改为需要的view

protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);     setContentView(R.layout.activity_test);     }

方法二:
使用LayoutInflater 绑定新的view

LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);        View view = inflater.inflate(R.layout.activity_test,null);

并在findViewById()中从该view中绑定

Button button = view.findViewById(R.id.button);

两种方法都可解决。

原创粉丝点击