2014-02-25 27 views
1

我想在我的ListView上使用CursorAdapter實現一種交替行效果,那就是如此特定的行讓我們說數字數據我想使用blue.xml作爲其佈局而文本行我想用他們的佈局red.xml。我從Sqlite獲取數據,所以我認爲使用CursorAdapter可能會更好,但我想知道CursorAdapter是否具有顯着優化的實現,因爲它使用查詢中的遊標與使用BaseAdapter相比。所以我正在尋找一些幫助,爲不同類型的行獲得交替行效果:例如。從CursorAdapter充氣多個視圖

Text - red_row 
Text - red_row 
Numbers - blue_row 
Text - red_row 
Numbers - blue_row 
Numers - blue_row 
Text - red_row 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     View retView; 
     Holder holder = new Holder(); 
     LayoutInflater inflater = LayoutInflater.from(context); 


    if(cursor.getString(cursor.getColumnIndex("from")).equals(myId)){ 

     retView = inflater.inflate(R.layout.row_red, parent, false); 
     holder.message = (TextView) retView.findViewById(R.id.msg1); 
     holder.time = (TextView) retView.findViewById(R.id.msg2); 
     holder.viewType = 1; 
    }else{ 
     retView = inflater.inflate(R.layout.row_blue, parent, false); 
     holder.message = (TextView) retView.findViewById(R.id.txt1); 
     holder.time = (TextView) retView.findViewById(R.id.txt1); 
     holder.viewType = 2; 
    } 


    retView.setTag(holder); 
    return retView; 
} 

@Override 
public void bindView(View view, Context context, Cursor cursor) { 
    Holder holder = (Holder)view.getTag(); 
    String message = cursor.getString(cursor.getColumnIndex("text")); 
    String time = cursor.getString(cursor.getColumnIndex("time")); 

     holder.message.setText(message); 
     holder.time.setText(time); 

} 


static class Holder{ 
    TextView message; 
    TextView time; 
    int viewType; 
} 

我嘗試上面的代碼和它的工作對所有可見的行,但一旦數據被滾動的所有新填充的行顯示了錯誤的佈局和我已經研究SQLite中的數據與該行的ID我想成爲一個特定的佈局是正確的,不知道究竟是什麼原因導致了這種情況,但是我將其縮小到newView方法中的某些內容,或者查詢對於滾動速率來說太慢,導致錯誤的佈局被誇大。任何幫助表示讚賞。

回答

0

解決方案1:

旁路光標適配器的默認實現,並覆蓋

public View getView(int position, View convertView, ViewGroup parent) {...} 

getViewTypeCount() { return 2} 

@Override 
public int getItemViewType(int position) { 
    return BLUE_vs_RED_logic(position); // return 0 or 1 
} 

像用於正常適配器。它應該工作正常。 (免責聲明:我從來沒那麼做,但看看https://stackoverflow.com/a/8617766/154272

解決方案2:

假設兩個視圖之間的差異不是太大(從一個內存使用點)。

創建一個包含兩種佈局的元行佈局。然後在bindView中隱藏/顯示你所需要的。

建議

如果你不使用的圖像,我會建議您的解決方案數量2