我以为我掌握了如何使用ViewHolders,但是现在运行此方法时会出现空指针异常。当我尝试为itemTitleView之一设置文本并且我不太了解我缺少的内容时,就会发生这种情况。我有三种使用不同背景颜色的布局,并且正在尝试根据ArrayList的特定元素的listViewItemType使用每种布局。我有一个Google商店,但对我来说还不清楚,可以提供任何帮助。
PostItemAdapter.java
public class PostItemAdapter extends ArrayAdapter<Item>
{
private LayoutInflater inflater;
private ArrayList<Item> datas;
public static final int TYPE_short = 0;
public static final int TYPE_med = 1;
public static final int TYPE_long = 2;
public PostItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects)
{
super(context, textViewResourceId, objects);
inflater = ((Activity) context).getLayoutInflater();
datas = objects;
}
//class to hold view object references
static class ViewHolder
{
TextView itemTitleView;
TextView itemTitleView1;
TextView itemTitleView2;
ImageView itemThumbView;
}
@Override
public int getItemViewType(int position) {
return datas.get(position).viewtype;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder;
int listViewItemType = getItemViewType(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.postitem, null);
viewHolder = new ViewHolder();
viewHolder.itemThumbView = (ImageView) convertView.findViewById(R.id.itemThumb);
if (listViewItemType == TYPE_short) {
viewHolder.itemTitleView = (TextView) convertView.findViewById(R.id.itemTitleLabel);
} else if (listViewItemType == TYPE_med) {
viewHolder.itemTitleView1 = (TextView) convertView.findViewById(R.id.itemTitleLabel1);
} else if (listViewItemType == TYPE_long) {
viewHolder.itemTitleView2 = (TextView) convertView.findViewById(R.id.itemTitleLabel2);
}
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (datas.get(position).itemThumbUrl == null)
{
viewHolder.itemThumbView.setImageResource(R.drawable.test);
}
viewHolder.itemTitleView.setText(datas.get(position).itemTitle);
viewHolder.itemTitleView1.setText(datas.get(position).itemTitle);
viewHolder.itemTitleView2.setText(datas.get(position).itemTitle);
return convertView;
}
}
最佳答案
将标题设置为if else
时需要添加TextView
语句。如果viewHolder.itemTitleView
不等于null
,则listViewItemType
将是TYPE_short
。
if (listViewItemType == TYPE_short) {
viewHolder.itemTitleView.setText(datas.get(position).itemTitle);
} else if (listViewItemType == TYPE_med) {
viewHolder.itemTitleView1.setText(datas.get(position).itemTitle);
} else if (listViewItemType == TYPE_long) {
viewHolder.itemTitleView2.setText(datas.get(position).itemTitle);
}