2013-05-13 42 views
0

我对Java很陌生。所以请原谅我问这样一个简单的问题。使用变量来指定R对象


要设置视图的背景图像,我可以做到这一点的

int TheButton = R.drawable.button1; 
button.setBackgroundResource(TheButton); 

但如何才能做到这一点,如果我想用一个变量来指定将R对象?

int a = 1; 
int TheButton = R.drawable["button"+a]; //this is what I'll do in javascript... 
button.setBackgroundResource(TheButton); 

回答

1

试试这个:

  String variable="button" + a; 
     int Button = getResources().getIdentifier(variable, "drawable", getPackageName()); 
     //Whatever you want to do.. 
1

在Android中,你不能访问资源的方式,因为当Android的编译你的应用程序将所有的这些字段值(INT)。

所以,你需要编写自己的映射得到你期待的结果,例如,你可以把所有的相关资源的数组:

int[] myResourceArray = new int[]{R.drawable.first, R.drawable.second ...}; 
button.setBackgroundResource(myResourceArray[0]); 
... 
button.setBackgroundResource(myResourceArray[1]); 

或者你可以使用的方式@Sercan建议,但根据Android的文档,他们不鼓励使用它出于性能原因。看看这里:getIdentifier()

0

好吧,首先,因为在java变量被键入,你不能添加一个int到字符序列。

其次,您不能使用字符串从类中调用公共变量(在本例中为自动生成的R类)。

第三点,如果tou想要在按钮上使用很多drawable并在它们之间切换,我建议您使用level-list drawable或者state-liste drawable。

看看:http://developer.android.com/guide/topics/resources/drawable-resource.html

1

当我们使用R.drawable.button1它是指int元素drawable类,这是在R类。 R.java是gen文件夹中的一个自生类。

所以int TheButton = R.drawable["button"+a];将无法​​正常工作。

,如果你想从指定JS一个特定的ID,那么你可以直接使用来自R.java复制的代码一样int TheButton =0x7f080002;从R.java

OR

int TheButton = getResources().getDrawable(R.drawable.button1); 
复制
相关问题