问题
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 button in color scheme 1, if there are files named button_1.png, button_2.png, button_3.png in drawable folder. (dynamically use different resource file for the same UI element based on the color scheme being used?)
Thanks,
回答1:
I've done something simular using getIdentifier():
int resId = context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
button.setBackgroundResource(resId);
回答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:
int resId = context.getResources().getIdentifier("button_1","drawable",context.getPackageName());
Button button = (Button view.findViewById(R.id.button1);
button.setBackgroundResource(resId);
I haven't tested this, but this should give you the idea.
回答3:
Put R.drawable.button_n
in an array int res[]
and then call them by button.setBackgroundResource(res[i])
来源:https://stackoverflow.com/questions/10656146/dynamically-change-the-name-of-the-resource-file-to-be-used