你能给我一些关于我的getView方法的建议吗;
我有自定义适配器,扩展ArrayAdapter(context,id,list)
public class myCustomAdapter extends ArrayAdapter{
private List obj = null;
public myCustomAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List objects) {
super(context, resource, objects);
obj = objects;
}
@Override
public int getCount() {
return obj.size();
}
@Nullable
@Override
public Object getItem(int position) {
return super.getItem(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Task myTask = (Task) getItem(position);
if(convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent);
}
TextView myTextView = (TextView) convertView.findViewById(R.id.textView);
myTextView.setText(myTask.getTaskText());
CheckBox myCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox);
myCheckBox.setChecked(myTask.getChecked());
return convertView;
}
}
问题1:super:未选中调用ArrayAdapter(..)作为原始类型的成员
问题3:getTaskText //来自我的Task类//可能会产生NPE
如果可能,我将不胜感激。
答案 0 :(得分:2)
if(convertView!=null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent);
}
应该是
if(convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent);
}
当convertview为null时,你必须膨胀。不是当它不为空。然后从你的getView()方法返回它
另外我看不到getCount()方法。告诉适配器有多少要充气的物品
也很重要答案 1 :(得分:1)
更改此
return super.getView(position, convertView, parent)
到
return convertView;
答案 2 :(得分:1)
当它为null时,你必须对convertview进行膨胀。
如果(convertView == NULL){ convertView = LayoutInflater.from(getContext())。inflate(R.layout.list_item,parent); }
还要返回convertview而不是super
答案 3 :(得分:0)
我建议使用BaseAdapter,它是基本的,ArrayAdapter是BaseAdapter的子类,在大多数情况下,你不需要继承BaseAdapter,直接使用它。
ArrayAdapter adapter = new ArrayAdapter(context, R.layout.list_item, R.id.text, stringList);
public class MyCustomAdapter extends BaseAdapter {
private List<Task> listData;
public MyCustomAdapter(List<Task> list) {
listData = list;
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
}
Task data = getItem(position);
TextView text = (TextView) convertView.findViewById(R.id.text);
return convertView;
}
}