Don
Don

Reputation: 987

setDrawable with dynamic parameter

I am using a listview with a basic adapter.

The XML code for each row is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/containerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView 
    android:id="@+id/imgView"
    android:layout_height="50dip"
    android:layout_width="50dip">        
</ImageView>

<TextView 
    android:id="@+id/descView"
    android:layout_toRightOf="@+id/imgView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TextView>
</RelativeLayout>

I am using an adapter to populate the relevant data in each row. Let's take the example to populate the text, it works well:

TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(<some dynamic data with whatever parameters and conditions>);

But when I want to do the same thing to populate dynamically the image, I am stuck:

ImageView iv = (ImageView)ll.findViewById(R.id.imgView);           
iv.setBackgroundResource(R.drawable.<problem is here since it has to be a static name of a file, not dynamic>)

Of course I could use a big switch like this

switch (<some dynamic parameter>) {
case 1: iv.setBackgroundResource(R.drawable.i1); break;
case 2: iv.setBackgroundResource(R.drawable.i2); break;
case 3: iv.setBackgroundResource(R.drawable.i3); break;

But that looks like a horrible choice, especially for long lists with thousands of images.

So how can I set images dynamically in this case without depending on a long and painful block of if else or a huge switch?

I hope this is clear, if no, please let me know I will do my best to clarify

Thanks

Upvotes: 0

Views: 542

Answers (2)

Pragnani
Pragnani

Reputation: 20155

Try this

for(int i=1;i<=100;i++)
{
int drawableid= this.getResources().getIdentifier("i"+i, "drawable", this.getPackageName());
iv.setBackgroundResource(drawableid);

}

Upvotes: 2

mstrengis
mstrengis

Reputation: 839

in Context getResources().getIdentifier("i1", "drawable", "your.package.name");

Upvotes: 0

Related Questions