2013-10-28 59 views
-1

我已經在Android中實現了自定義CursorAdapter而不使用from to模式,以便能夠廣泛地重用我的適配器我想將其添加到我的適配器。我該怎麼做呢?如何在我的自定義CursorAdapter中實現從 - 到模式

這是我的適配器:

 public class AtomAdapter extends CursorAdapter { 

LayoutInflater inflater; 
@SuppressWarnings("deprecation") 
public AtomAdapter(Context context, Cursor c) { 
    super(context, c); 
    inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    //will create a new View only when recycling an older View is not possible 
    View v= inflater.inflate(R.layout.layout_row, parent,false); 
    TextView tv=(TextView)v.findViewById(R.id.txt_title); 
    v.setTag(R.id.txt_title,tv); 
    TextView tv2=(TextView)v.findViewById(R.id.txt_content); 
    v.setTag(R.id.txt_content,tv2); 
    return v; 
} 

@Override 
public void bindView(View view, Context context, Cursor cursor) { 
    // bind data to your row 
    TextView txt_title=(TextView)view.getTag(R.id.txt_title); 
    TextView txt_content=(TextView)view.getTag(R.id.txt_content); 
    txt_title.setText(cursor.getString(cursor.getColumnIndex(AtomDB.TITLE))); 
    txt_content.setText(cursor.getString(cursor.getColumnIndex(AtomDB.CONTENT))); 
} 

} 

回答

0

我讀SimpleCursorAdapter源代碼,並發現這兩種方法可能會出現一些主動幫助第一種方法中,從findColumns列名轉換爲列索引:

  private void findColumns(String[] from) { 
      if (mCursor != null) { 
       int i; 
       int count = from.length; 
       if (mFrom == null || mFrom.length != count) { 
        mFrom = new int[count]; 
      } 
      for (i = 0; i < count; i++) { 
        mFrom[i] = mCursor.getColumnIndexOrThrow(from[i]); 
      } 
      } 
      else { 
     mFrom = null; 
    } 
} 

第二種方法是bindView方法,您可以在其中調用更具體的方法,例如setViewTextsetViewImage

 @Override 
     public void bindView(View view,Context context,Cursor cursor) 
     { 
     final int[] from=mFrom; 
     final int[] to=mTo; 
     for(int i=0;i<mTo.length;i++) 
     { 
      String text=cursor.getString(from[i]); 
      if(text==null) 
      text="No text found"; 
      if(view instanceof TextView) 
      setViewText((TextView)v,text); 
      else if(view instanceof ImageView) 
      setViewImage((ImageView)v,text); 
      else 
      throw new IllegalStateException(v.getClass().getName()+" is not a View that can be bound by SimpleCursorAdapter"); 
     }  
} 

setImageUri主UI線程上運行的方法,這可能會導致延遲。

相關問題