3

看起來有兩種可能的方式來改變的東西在ListView行:setViewBinder/setViewValue和getView/LayoutInflater的用法有什麼區別?

  1. 使用setViewBinder/setViewValue

    myCursor.setViewBinder(新SimpleCursorAdapter.ViewBinder(){

    @Override 
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
        int viewId = view.getId(); 
        switch(viewId) { 
        case R.id.icon: 
         // change something related to the icon here 
    
  2. 使用getView/LayoutInflater

    公共查看getView(INT位置,查看convertView,ViewGroup以及母公司){

    View itemView = null; 
    
        if (convertView == null) { 
         LayoutInflater inflater = (LayoutInflater) parent.getContext() 
           .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
         itemView = inflater.inflate(R.layout.list_row, null); 
        } else { 
         itemView = convertView; 
        } 
    
        ImageView imgViewChecked = (ImageView) itemView 
          .findViewById(R.id.icon); 
        // change something related to the icon here 
    

的是這兩種方法之間的區別?

回答

3

您可以使用它們來完成相同的任務。 SimpleCursorAdapter添加了ViewBinder系統,使您更容易,因此您不必編寫整個getView代碼。

public View getView(int position, View convertView, ViewGroup parent) { 
    if (!mDataValid) { 
    throw new IllegalStateException(
     "this should only be called when the cursor is valid"); 
    } 
    if (!mCursor.moveToPosition(position)) { 
    throw new IllegalStateException("couldn't move cursor to position " 
     + position); 
    } 
    View v; 
    if (convertView == null) { 
    v = newView(mContext, mCursor, parent); 
    } else { 
    v = convertView; 
    } 
    bindView(v, mContext, mCursor); 
    return v; 
} 


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"); 
     } 
     } 
    } 
    } 
} 
:其實,SimpleCursorAdapter只是通過調用setViewValue方法(與標準的樣板錯誤檢查和沿充氣)

我已經附加了Android的源代碼SimpleCursorAdapter用來getView實施實現getView