0

I'm a little stuck at the moment. I know similar questions have been asked, but I haven't been able to find anything that has helped.

I'm trying to get and image to appear in ListView from an internal database inside my android application. I have a database with 141 rows, and each row is labeled 1,2 or 3. I need a different png image (saved in my res/drawable folder) to show depending on the 1,2, or 3. Here is my current Query. Any advice would be welcome. I realize there may be a better way to display the info I need.

   public void whosnext(View view) {
    // || is the concatenation operation in SQLite
    cursor = db.rawQuery("SELECT * FROM eventsv1 WHERE start_time > (DATETIME('now')) AND title LIKE ? ORDER BY date ASC, time DESC", 
                    new String[]{"%" + searchText.getText().toString() + "%"});
    adapter = new SimpleCursorAdapter(
            this, 
            R.layout.artist_list_item, 
            cursor, 
            new String[] {"title", "time", "date", "title3", "style"}, 
            new int[] {R.id.title, R.id.time, R.id.date, R.id.title3, R.id.style});
    setListAdapter(adapter);
}
4

2 回答 2

1

我会写一个自定义 CursorAdapter

public class WhosNextAdapter extends CursorAdapter
{
    public WhosNextAdapter(Context context, Cursor cursor, boolean autoRequery) {
        super(context, cursor, autoRequery);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //This is were you would check your cursor for style (I think that is 1,2,3 your column)
        int style = cursor.getInt(cursor.getColumnIndex("style"));

        ImageView img = (ImageView) view.findViewById(R.id.yourImageViewId);

        switch (style) {
            case 1:
                img.setImageResource(R.drawable.yourImageForStyle1);

            break;
            case 2:
                img.setImageResource(R.drawable.yourImageForStyle2);

            break;

//etc.
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        //Inflate layout R.layout.artist_list_item

        //Call bindView passing inflated layout, context, and cursor

        //return layout
    }
}
于 2011-06-27T17:06:35.450 回答
0

您肯定需要扩展SimpleCursorAdapter,如果您的项目布局足够简单,您唯一需要做的就是覆盖setViewImage()方法,您只需从数据库转换提供的值并调用对象setImageResource()上的方法。ImageView这样您就不必更改很多附加代码。

public class MySimpleCursorAdpater extends SimpleCursorAdapter {

    public MySimpleCursorAdpater(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    @Override
    public void setViewImage(ImageView v, String value) {
        /*your code to convert value from database to drawable resource id*/
        v.setImageResource(resourceId);
    }

}
于 2011-06-27T18:10:10.823 回答