Skip to content Skip to sidebar Skip to footer

Dynamically Change The Name Of The Resource File To Be Used?

It is possible to do something like: if (colorScheme == 1) button.setBackgroundResource(R.drawable.button + '_1') in order to use R.drawable.button_1 as the resource for this

Solution 1:

I've done something simular using getIdentifier():

int resId = context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
button.setBackgroundResource(resId);

Solution 2:

In order for it to be dynamic, there will be some code required. You can set up your layout in xml Like this:

<Button 
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

And then reference it in your code like this:

intresId= context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
Buttonbutton= (Button view.findViewById(R.id.button1);
button.setBackgroundResource(resId);

I haven't tested this, but this should give you the idea.

Solution 3:

Put R.drawable.button_n in an array int res[] and then call them by button.setBackgroundResource(res[i])

Post a Comment for "Dynamically Change The Name Of The Resource File To Be Used?"