我正在尝试创建一个自定义cursoradapter,它将根据游标中的某些数据使用两种不同的布局。我一直在阅读'覆盖getViewTypeCount()和getItemViewType()'来实现这一点,但我似乎无法弄清楚如何实现它。
这是我的bindView代码和新的View方法:
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tView = (TextView) view.findViewById(R.id.TextView1);
tView.setText("The text");
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.item1, parent, false);
}
修改 现在我得到了这个工作,但是我想根据光标中的一些数据选择使用什么rowlayout而我无法正常工作..有人有想法吗?
@Override
public int getItemViewType(int position) {
return position % 2;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtAddress
.setText("blabla");
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View v = null;
int type = cursor.getPosition() % 2;
if(type == 0) {
v = mInflater.inflate(R.layout.item, parent, false);
} else {
v = mInflater.inflate(R.layout.item2, parent, false);
}
holder.txtAddress = (TextView) v.findViewById(R.id.tvName);
v.setTag(holder);
return v;
}
答案 0 :(得分:92)
所以我终于明白了。对于那些感兴趣的人,工作代码如下:
private int getItemViewType(Cursor cursor) {
String type = cursor.getString(cursor.getColumnIndex("type"));
if (type.equals("1")) {
return 0;
} else {
return 1;
}
}
@Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.textView
.setText(cursor.getString(cursor.getColumnIndex("body")));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View v = null;
if (cursor.getString(cursor.getColumnIndex("type")).equals("1")) {
v = mInflater.inflate(R.layout.message1, parent, false);
holder.textView = (TextView) v
.findViewById(R.id.textView1);
} else {
v = mInflater.inflate(R.layout.message2, parent, false);
holder.textView = (TextView) v
.findViewById(R.id.textView2);
}
v.setTag(holder);
return v;
}
public static class ViewHolder {
public TextView textView;
}
答案 1 :(得分:2)
看看这个example,您可以轻松地对其进行调整以解决您的问题。这很简单。
答案 2 :(得分:0)
关于在getItemViewType方法中访问游标的另一个可能的解决方案如下:
@Override
public int getChildType(int groupPosition, int childPosition) {
Cursor c = getChild(groupPosition, childPosition);
if(c.getString(c.getColumnIndex(Contract.MyColumn)).equals("value"))
return 0;
else return 1;
}