2009-08-20 62 views
2

我使用此代码从光标获取项目,但它只是返回列表中的一个项目。那么,我如何才能将所有项目都列入我的列表,这是我的代码?从android中的光标获取所有项目

class MyAdapter extends SimpleCursorAdapter 
{ 
    private Context context; 

    public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) 
    { 
     super(context, layout, c, from, to); 
     this.context = context; 

    } 
    public View getView(int position, View convertView, ViewGroup parent){ 
     Cursor cursor = getCursor(); 

     LayoutInflater inflater = ((Activity) context).getLayoutInflater();   
     View v = inflater.inflate(R.layout.sbooks_row, null);   
     TextView title = (TextView)findViewById(R.id.title); 
     if(title != null){ 
      int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE); 
      String type = cursor.getString(index); 
      title.setText(type); 
     } 

     TextView lyrics = (TextView)findViewById(R.id.lyrics); 
     if(lyrics != null){ 
      int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_LYRICS); 
      String type = cursor.getString(index); 
      lyrics.setText(type); 
     } 

     ImageView im = (ImageView)findViewById(R.id.icon); 
     if(im!=null){ 
      int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_FAVORITE); 
      int type = cursor.getInt(index); 
      if(type==1){ 
       im.setImageResource(android.R.drawable.btn_star_big_on); 
      } 
      else{ 
       im.setImageResource(android.R.drawable.btn_star_big_off); 
      } 
     } 

     return v; 
    } 

回答

5

CursorAdapter的表现比其他列表适配器有点不同 - 而不是getView(),魔术在这里NewView的()和bindView()会发生,所以我觉得getView()是不正确的方法来覆盖。

您可能只会得到一个结果,因为在创建第一行之后,CursorAdapter希望bindView()插入新数据并重用已经膨胀的行,并且您期望getView()可以实现这一点。

我建议你尝试将你的代码移动到newView()来扩展你的视图,bindView()来执行填充行的实际逻辑。

祝你好运,并让我们更新结果。

+0

嗨,我尝试编辑我的代码与您的意见。我使用newView(),bindView()函数,并返回所有项目。 但我仍然有问题在我的列表视图中,它显示不正常。我的意思是,当我将scollbar上下拖动时,它显示不同。我可以忘记一些事吗? – Dennie 2009-08-23 10:46:48

+0

你是什么意思的项目不正常显示?如果您看到旧物品出现,而不是新物品(发生在我身上的普通适配器),则回收逻辑(bindView())应该存在问题。 P.S.I还建议您使用ViewHolder模式,如下所述:http://www.youtube.com/watch?v = N6YdwzAvwOA at 0:09:02。 – 2009-08-23 12:34:04

+0

该视频链接对于任何想了解ListView下发生了什么的人都很有帮助。谢谢Dimitar! – 2010-08-20 21:25:30

0

我假设由getCursor()方法返回正确检索所有的行,你的表指针,你必须明确地将光标移动到的位置访问数据的行之前,因此在你必须调用getView()方法的开始。

cursor.moveToPosition(position); 
+0

它还会返回一个项目!我认为它在这里不起作用。 – Dennie 2009-08-23 10:35:46

相关问题