我想要的是在 ListView 的每一行中包含不同类型的项目的 ListView 。我知道我需要使用扩展 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.
}
}
但是当我运行这个 Activity 时我得到了错误:
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
我明白为什么,但我不打算在我的所有布局中使用 textView。我需要一些关于如何进行的指导。谢谢
在我的 item1.xml 中更改 linearLayout 父级的背景会导致空指针异常。如果我保留原来的背景,它确实可以在没有空指针异常的情况下工作
最佳答案
您的 ArrayAdapter
实现本来可以工作,但是您需要返回您在 getView()
方法中膨胀的行 View
,而不是委托(delegate)给 super 实现。
关于java - 自定义适配器以制作具有不同项目的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928528/