问题
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);
}
回答1:
I would write a custome 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
}
}
回答2:
You definitely need to extend SimpleCursorAdapter
and if your item layout is simple enough, the only thing you need to do is to override setViewImage()
method where you simply convert provided value from the database and call setImageResource()
method on the ImageView
object. Then you won't have to alternate much your attached code.
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);
}
}
来源:https://stackoverflow.com/questions/6496195/displaying-an-image-in-listview-from-sqlite-database