Android SimpleCursorAdapter - Adding conditional images

蹲街弑〆低调 提交于 2019-12-19 04:12:10

问题


So I'm using SimpleCursorAdapter to adapt data from SQLite into ListView. Lets call this database testData. One of my columns in testData records true or false with either 0 or 1. Can I make the listview display a different image for each item according to whether that row has 0 or 1?

This is the adapter that I'm using.

ListAdapter adapter = new SimpleCursorAdapter(
this, 
android.R.layout.two_line_list_item,  
mCursor,                                              
new String[] {testData.DATE1, testData.NAME1},           
new int[] {android.R.id.text1, android.R.id.text2}); 

回答1:


I created a customized SimpleCursorAdapter:

public class MySimpleCursorAdapter extends SimpleCursorAdapter {

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

    @Override public void setViewImage(ImageView iv, String text)
    {
        if (text.equals("0")) {
            iv.setImageResource(R.drawable.new1);
        }
        else {
            iv.setImageResource(R.drawable.check1);
        }
    }

}

In my ListActivity I bind the text field in the database to the image resource id. In your example it would look like this:

ListAdapter adapter = new MySimpleCursorAdapter(
    this, 
    android.R.layout.two_line_list_item,  
    mCursor,                                              
    new String[] {testData.DATE1, testData.NAME1},           
    new int[] {android.R.id.text1, android.R.id.image1}); // Note: replace text2 with image1

I.e. if the text field "Name1" in your database contains "0", the image "new1" will be displayed in the ListView, and if it has another value, "check1" will be displayed.



来源:https://stackoverflow.com/questions/7439609/android-simplecursoradapter-adding-conditional-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!