简体   繁体   中英

displaying flag image in listview from sqlite database

I have a database with a "flagname" field. What I want to do is display a listview with the relevant flag in the image view that corresponds with the database field, along side a text field. The text field from the database is being displayed ok, but I'm having trouble displaying the relevant flag beside it. Can someone please let me know where I'm going wrong. My code is listed below:

public class favourites extends Activity{

Cursor cursor;
ListView lv;
ImageView iv;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.listmain);  
    iv = (ImageView)findViewById(R.id.imgFlag);


    DBAdapter db = new DBAdapter(this);
    db.open();

    lv = (ListView)findViewById(R.id.list);

    //Get cursor for list items
    cursor = db.getAllRadioStations();

    //assign fields to columns
    String[] columns = new String[]{DBAdapter.KEY_STATION_NAME.toString()};
    int[] to = new int[]{R.id.txtFlag};

    startManagingCursor(cursor);

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.flagchoice, cursor, columns, to);

    lv.setAdapter(adapter);
    lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);



}

What you need to do is override the Adapter.setViewBinder(). Try this:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.flagchoice, cursor, columns, to);

adapter.setViewBinder(new ViewBinder() {

public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {

String country=aCursor.getString(aColumnIndex);

int id = getResources().getIdentifier("yourpackagename:drawable/" + country , null, null);

iv = (ImageView)findViewById(R.id.imgFlag);

iv.setImageDrawable(getResources().getDrawable(id));

TextView tv=(TextView) aView;
tv.setText(aCursor.getString(aColumnIndex));
return true;

}
});
lv.setAdapter(adapter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM