为何我按照老师的方法用inflater.inflate,会报空指针
我按照教程尝试编写自定义Adapter,继承BaseAdapter,在重写getView方法时,使用了
convertView = inflater.inflate(R.layout.lv_test_list,null); 然而在运行时就报错了,显示 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup)' on a null object reference。
但是,视频教程就是这么写的~~如下图所示,第70行代码。请问我的问题出在哪里?我该如何修改?
我的代码如下:
public class ListAdapter extends BaseAdapter { private List<ListAdapterItem> items; LayoutInflater inflater; public ListAdapter(Context context,List<ListAdapterItem> source){ items = source; inflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if(convertView == null){ convertView = inflater.inflate(R.layout.lv_test_list,null); ImageView img = (ImageView) convertView.findViewById(R.id.img_icon); TextView tv_title = (TextView) convertView.findViewById(R.id.tv_title); TextView tv_content = (TextView) convertView.findViewById(R.id.tv_content); vh = new ViewHolder(); vh.content = tv_content; vh.title = tv_title; vh.img = img; convertView.setTag(vh); } else{ vh = (ViewHolder) convertView.getTag(); } ListAdapterItem item = items.get(position); vh.content.setText(item.str_content); vh.title.setText(item.str_title); vh.img.setImageResource(item.int_img); return convertView; } class ViewHolder { public ImageView img; public TextView title; public TextView content; } }