【发布时间】:2014-01-05 00:29:38
【问题描述】:
我想要的是在列表视图的每一行中都有一个包含不同类型项目的列表视图。我知道我需要使用扩展 BaseAdapter 而不是 ArrayAdapter 的自定义适配器,但之后我不知道如何解决这个问题。以前我尝试过制作这样的适配器:
public class MyArrayAdapter<T> extends ArrayAdapter<T> {
LayoutInflater mInflater;
int[] mLayoutResourceIds;
private final Context context;
public MyArrayAdapter(Context context, int[] textViewResourceId, List<T> objects) {
super(context, textViewResourceId[0], objects);
this.context = context;
mInflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
mLayoutResourceIds = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
int type = getItemViewType(position);
// instead of if else you can use a case
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == TYPE_ITEM1) {
//infalte layout of type1
row = inflater.inflate(R.layout.item1, parent, false);
}
if (type == TYPE_ITEM2) {
//infalte layout of type2
} else {
//infalte layout of normaltype
}
}
return super.getView(position, convertView, parent);
}
@Override
public int getItemViewType(int position) {
if (position== 0){
type = TYPE_ITEM1;
} else if (position == 1){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type; //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public int getViewTypeCount() {
return 3; //To change body of overridden methods use File | Settings | File Templates.
}
}
但是当我运行活动时,我得到了错误:
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
我明白为什么,但我不打算在我的所有布局中使用 textView。我需要一些关于如何进行的指导。谢谢
在我的 item1.xml 中更改 linearLayout 父级的背景会导致空指针异常。如果我保持原来的背景,它确实可以在没有空指针异常的情况下工作
【问题讨论】:
-
您能描述一下“不同类型的项目”是什么意思吗?一般有几种方法。您可以有一个 CustomerAdapter
,其中 T 是一个接口,然后每个实现类都有自己的 getView() 和用于在列表中显示元素的相关方法。 -
意思是一行会有一个switch和一个textView,另一行会有几个imageView和一个textView,最后一个会有一个switch和一个textView
-
哦,好吧,在这种情况下,我认为您的方法很好,只需使用 BaseAdapter 而不是 ArrayAdapter,您就不必担心 textview resourceId。
标签: java android listview android-listview