2013-10-02 51 views
0

我想延長SimpleCursorAdapter,涉及一種} else if (c instanceof MyView) { setMyViewMyThing(MyView v, text)添加到bindView方法。如何擴展Android的SimpleCursorAdapter?

public void bindView(View view, Context context, Cursor cursor) { 
    final ViewBinder binder = mViewBinder; 
    final int count = mTo.length; 
    final int[] from = mFrom; 
    final int[] to = mTo; 

    for (int i = 0; i < count; i++) { 
     final View v = view.findViewById(to[i]); 
     if (v != null) { 
      boolean bound = false; 
      if (binder != null) { 
       bound = binder.setViewValue(v, cursor, from[i]); 
      } 

      if (!bound) { 
       String text = cursor.getString(from[i]); 
       if (text == null) { 
        text = ""; 
       } 

       if (v instanceof TextView) { 
        setViewText((TextView) v, text); 
       } else if (v instanceof ImageView) { 
        setViewImage((ImageView) v, text); 
       } else { 
        throw new IllegalStateException(v.getClass().getName() + " is not a " + 
          " view that can be bounds by this SimpleCursorAdapter"); 
       } 
      } 
     } 
    } 
} 

事實上,mViewBindermTomFrom是SimpleCursorAdpater的私有成員阻止我這樣做。

有沒有更好的方法來實現我的目標,而不是將SimpleCursorAdapter批發的來源複製到MyCursorView並將我的條件添加到bindView? (這個解決方案可以工作,並且速度很快,但是會很糟糕的做法。)

(在一個元級別上,它看起來像Android作者交易了我自由地擴展SimpleCursorAdapter,以便他們改變實現的自由。有沒有可以既保留任何語言?)

+0

不應該設置自定義聯編程序嗎? – njzk2

回答

3

如何延長Android的SimpleCursorView?

Android中沒有SimpleCursorView。對於這個答案的其餘部分,我會推測你指的是to SimpleCursorAdapter

我想擴展SimpleCursorView,爲bindView方法添加一個} else if(c instanceof MyView){setMyViewMyThing(MyView v,text)。

其他人都會use setViewBinder()提供their own ViewBinder。引用的文檔ViewBinder

你應該使用這個類來從光標將值綁定到不直接由SimpleCursorAdapter支持的觀點或更改綁定發生由SimpleCursorAdapter支持意見的方式。

當然,你不必這樣做。

是否有更好的方式來實現我的目標比複製SimpleCursorView批發來源到MyCursorView並添加我的條件bindView?

除了使用ViewBinder?可能不會。

在meta級別上,它看起來像Android作者已經交易了我自由地擴展SimpleCursorView,以便他們改變實現的自由。

「在元級別上」,它看起來像Android作者favored composition over inheritance

+0

謝謝,你完全正確,我忽略了'ViewBinder'。擴展'ResourceCursorAdapter'看起來更簡單,使用'ViewBinder',所以我會先試一試。 – fadedbee

1

你想實現應該是一個可行的SimpleCursorAdapter.ViewBinder什麼。實現其中之一,並在setViewValue(View view, Cursor cursor, int columnIndex)函數返回false如果view是不是你MyView的實例。然後,撥打SimpleCursorAdapter.setViewBinder(SimpleCursorAdapter.ViewBinder viewBinder),傳遞您的ViewBinder作爲參數。根據文檔(與您發佈實施),如果ViewBinder不能處理View型(即它返回false),bindView()將回落到默認的實現。