Dynamically change the name of the resource file to be used?

我的梦境 提交于 2019-12-11 05:31:04

问题


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

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