Android自定义view,空指针异常求解决

2025-05-22 02:15:04
推荐回答(2个)
回答1:

这里 LinearLayout l=(LinearLayout)findViewById(R.id.LinearLayout);写错了,后边是获取的Id。这里空指针异常。

解决方法为:

inflate控件加载注意空指针:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

获得 LayoutInflater 实例的三种方式:

1.LayoutInflater infalte=context.getSytemService(Context.LAYOUT_INFLATE_SERVICE);

2.LayoutInflater inflater = getLayoutInflater();  //调用Activity的getLayoutInflater()

3.LayoutInflater flater = LayoutInflater.from(this);


回答2:

你是不是这里 LinearLayout l=(LinearLayout)findViewById(R.id.LinearLayout);写错了,后边应该是获取的Id吧。估计是这里空指针异常。