这是必要的代码。我试图在同一列表视图中为行使用两个不同的视图。我希望将一组arraylist膨胀为行,然后再膨胀。但是,行会一个接一个地膨胀。
代码:
@Override
public int getItemViewType(int position) {
if (position < (mContactsNumber.size())) {
a = 0;
return a;
} else {
a = 1;
return a;
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final int pos = i;
int type = getItemViewType(i);
View v = view;
if (view == null) {
switch (type) {
case 0:
v = mInflater.inflate(R.layout.contacts_row, null);
name = (TextView) v.findViewById(R.id.contact_name);
name.setText(mContactsNames.get(i));
break;
case 1:
v = mInflater.inflate(R.layout.manual_row, null);
mManual = (TextView) v.findViewById(R.id.manual_number);
mSwitch = (SwitchCompat) v.findViewById(R.id.manual_switch);
mManual.setText(mPermanentManual.get(i));
mSwitch.setTag(i);
try {
if (mManualList.contains(mPermanentManual.get(i))) {
mSwitch.setChecked(true);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return v;
}
答案 0 :(得分:1)
我认为当convertView
不为空时会出现问题,因为您的else
方法中没有getView
语句。
您可以使用ItemViewType
将您的适配器更改为以下内容:
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM_0 = 0;
private static final int TYPE_ITEM_1 = 1;
private static final int TYPE_MAX_COUNT = 2;
...
@Override
public int getItemViewType(int position) {
return (position < (mContactsNumber.size()) ? TYPE_ITEM_0 : TYPE_ITEM_1;
}
@Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
@Override
public String getItem(int position) {
return mData.get(position);
}
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM_0:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_ITEM_1:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}