gpt4 book ai didi

java - 如何在单个适配器中使用两个 Viewholder

转载 作者:行者123 更新时间:2023-11-29 07:49:52 27 4
gpt4 key购买 nike

我在 ListView 中使用分段时遇到问题。我需要使用 viewholder 使 listview 滚动平滑,但我不知道如何实现两个 viewholders,因为有两个单独的 View ,一个是部分,第二个是简单的条目。这是我尝试过的代码和我得到的错误。请告诉我哪里做错了,我该如何改正:

代码

@
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)

最佳答案

您需要覆盖 ListAdapter 中的 getItemViewType(),为每种类型的行返回一个不同的数字。在您的情况下,您可以为部分返回 0,为常规行返回 1。然后,将使用适当的 View 类型调用 getView() 以进行回收。

@Override
public int getItemViewType(int position) {
if (getItem(position).isSection()) {
return(0);
}

return(1);
}

关于java - 如何在单个适配器中使用两个 Viewholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com