在listview中使用切片时遇到问题。我需要使用viewholder使listview滚动顺利,但我不知道如何实现两个视图,因为两个单独的视图一个是节,第二个是简单的条目。这是我尝试的代码和我得到的错误。请告诉我我在哪里做错了,我该如何纠正呢:
CODE
@
Override
public View getView(int position, View convertView, ViewGroup parent) {
final GroupAccountdto i = items.get(position);
if (i != null) {
if (i.isSection()) {
if (convertView == null) {
convertView = vi.inflate(R.layout.list_group_section, null);
ViewHolderGroup group_holder = new ViewHolderGroup();
group_holder.group_name = (TextView) convertView.findViewById(R.id.list_section_group_name);
convertView.setTag(group_holder);
}
ViewHolderGroup group_holder = (ViewHolderGroup) convertView.getTag();
GiddhGroups si = (GiddhGroups) i;
group_holder.group_name.setText(si.getGroupname());
} else {
if (convertView == null) {
convertView = vi.inflate(R.layout.list_item_account, null);
ViewHolderAccount account_holder = new ViewHolderAccount();
account_holder.account_name = (TextView) convertView.findViewById(R.id.list_item_account_name);
account_holder.account_bal = (TextView) convertView.findViewById(R.id.list_item_account_balance);
}
ViewHolderAccount account_holder = (ViewHolderAccount) convertView.getTag();
GiddhAccounts ei = (GiddhAccounts) i;
if (account_holder.account_name != null)
account_holder.account_name.setText(ei.getAccountName());
if (account_holder.account_bal != null)
account_holder.account_bal.setText(ei.getBalance());
}
}
return convertView;
}
static class ViewHolderGroup {
TextView group_name;
}
static class ViewHolderAccount {
public TextView account_name;
public TextView account_bal;
}
错误
02-27 12:49:28.461: E/AndroidRuntime(20200): java.lang.ClassCastException: adapters.GroupAccountAdapter$ViewHolderGroup cannot be cast to adapters.GroupAccountAdapter$ViewHolderAccount
02-27 12:49:28.461: E/AndroidRuntime(20200): at adapters.GroupAccountAdapter.getView(GroupAccountAdapter.java:53)
02-27 12:49:28.461: E/AndroidRuntime(20200): at android.widget.AbsListView.obtainView(AbsListView.java:2334)
02-27 12:49:28.461: E/AndroidRuntime(20200): at android.widget.ListView.measureHeightOfChildren(ListView.java:1409)
02-27 12:49:28.461: E/AndroidRuntime(20200): at android.widget.ListView.onMeasure(ListView.java:1273)
答案 0 :(得分:5)
您需要覆盖getItemViewType()
中的ListAdapter
,为每种类型的行返回一个不同的数字。在您的情况下,您可以为部分返回0
,为常规行返回1
。然后,getView()
将使用适当的View
类型进行调用以进行回收。
@Override
public int getItemViewType(int position) {
if (getItem(position).isSection()) {
return(0);
}
return(1);
}