我使用此代码从光标获取项目,但它只返回列表中的一个项目。那么,我怎样才能将所有项目都列入我的列表,这是我的代码?
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;
}
答案 0 :(得分:5)
CursorAdapter的行为与其他列表适配器略有不同 - 而不是在getView()中,这里的魔法发生在newView()和bindView()中,所以我认为getView()不是正确的覆盖方法。
你可能只得到一个结果,因为在创建第一行之后,CursorAdapter期望bindView()插入新数据并重用已经膨胀的行,并且你希望getView()能够做到这一点。
我建议你尝试将代码移动到newView()以扩展视图,并使用bindView()来执行填充行的实际逻辑。
祝你好运,并让我们及时了解结果。
答案 1 :(得分:0)
我假设getCursor()方法返回的游标正确地检索了表的所有行,你必须在访问行的数据之前显式地将光标移动到一个位置,所以在getView的开头()方法你必须打电话。
cursor.moveToPosition(position);