2

我使用此代码从光标中获取项目,但它只返回我列表中的一项。那么,我怎样才能将所有项目都添加到我的列表中,这是我的代码?

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;
    }
4

2 回答 2

5

CursorAdapter 的行为与其他列表适配器略有不同 - 而不是在 getView() 中,这里的魔法发生在 newView() 和 bindView() 中,所以我认为 getView() 不是正确的覆盖方法。

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

我建议您尝试将代码移至 newView() 以扩展您的视图,并尝试将 bindView() 移至执行填充行的实际逻辑。

祝你好运,让我们随时了解结果。

于 2009-08-21T21:42:26.443 回答
0

我假设 getCursor() 方法返回的游标正在正确检索表的所有行,您必须在访问一行数据之前显式地将游标移动到某个位置,因此在 getView() 方法的开头你必须打电话。

cursor.moveToPosition(position);
于 2009-08-21T12:18:32.410 回答