Search code examples
androidlistviewimageviewsimplecursoradapter

How can I change an ImageView's source programmaticaly


I have overwritten the bindView method in my custom CursorAdapter.

I need to set an image resource for each view of the ListView.

R.drawable.innervate is the name of the image in the res/drawable/ folder.

The setImageResource methods takes as a parameter only integers, however I only know the name of my resources.

How can I change the image resource of my image view if I only know the name of the resources.

public void bindView(View view, Context arg1, Cursor cursor) 
{

    TextView textView = (TextView) view.findViewById(R.id.label);
    textView.setText(cursor.getString(1));

    ImageView imageView = (ImageView) view.findViewById(R.id.icon);
    imageView.setImageResource(R.drawable.innervate);       
}

The data of the image resource is taken from a cursor. So, I'm retrieving the names of the pictures from my database and the pictures are in my res/drawable/ folder.


Solution

  • You want to use:

    context.getResources().getIdentifier("drawableName", "drawable", context.getPackageName());
    

    Here is an example of a static method that you can use to get the resource id of any drawable that you know it's name. (Must be in the res/drawable folders)

    public static int getDrawableId(Context context, String nameOfDrawable) {
        return context.getResources().getIdentifier(nameOfDrawable, "drawable", context.getPackageName());
    }
    

    So an example using my method above:

    imageView.setImageResource(getDrawableId(this, "innervate"));