1

我在使用列表視圖中的切片時遇到問題。我需要使用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) 

回答

5

你需要重寫getItemViewType()在您的ListAdapter中,爲每種類型的行返回一個不同的數字。在你的情況下,你可以返回0部分和1爲常規行。然後,getView()將被調用適當的View類型進行回收。

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

    return(1); 
} 
+0

謝謝回答。做你有任何樣品???當我這樣做第一次看有點複雜 –

+0

@Bansal_Sneha:見更新的答案。 – CommonsWare

相關問題