它是一件好事,基于ID的R.java机器人产生的十六进制值编写逻辑 [英] Is it a good thing to write logic based on the hex value of id generated in R.java android
问题描述
这是我所看到的Android应用程序。他们有一些图像按钮与IDS
This what I have seen in an android application. They have a number of image buttons with ids
R.java :
public static final int img1=0x7f090080;
public static final int img2=0x7f090081;
public static final int img3=0x7f090082;
public static final int img4=0x7f090083;
public static final int img5=0x7f090084;
public static final int img6=0x7f090085;
public static final int img7=0x7f090086;
public static final int img8=0x7f090087;
在活动中的一个,他们正在穿越一个for循环如下图所示:
In one of the activity they are traversing a for loop like below:
for (int i = 0; i < NoOfButtons; i++) {
if (i == pos) {
((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_red);
} else {
((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_brown);
}
我想知道它是多么安全和适宜的。 有一件事,这是工作的精绝。我是其中的一部分,从个月,从来没有见过一个问题,在这样的逻辑。但它仍然惹恼了我一下。
I want to know how much safe and advisable it is. One thing this is working absolutely fine. I been a part of this from months and never seen a problem in this logic. But still it irks me a bit.
注:我没有收到任何错误,我知道了替代的解决方案也。我唯一担心的是,如果这是不可取/安全,我想知道为什么吗?另一种是场景,它可以为我制造混乱。我对R.java一个很好的了解。
Note : I am not getting any error and I know the alternate solution also. My only concern is if it is not advisable/safe I want to know why? Another is scenarios where it can create havoc for me. I have a good understanding about R.java.
推荐答案
您可能需要使用反射
添加这个方法到code:
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
和使用这样的:
int myID =
getResourceID("your_resource_name", "drawable", getApplicationContext());
注:没有路径(没有扩展名,如遇图像)
Note: no path (and no extension, in case of images).
这篇关于它是一件好事,基于ID的R.java机器人产生的十六进制值编写逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!