[英]Creating Dynamic R.drawable source and ImageView
I have an Activity which has variable position
that comes from another activity. 我有一个Activity,它有来自另一个活动的可变
position
。 I handle this variable with Intent
like below. 我用
Intent
处理这个变量,如下所示。 ( Actually position
is listView's position from another activity. ) and values of position
variable are 0 to 200 ( 实际上,
position
是listView从另一个活动开始的位置。 ) position
变量的值是0到200
I took my Extra, then assigned it to a string than I parsed it to an Integer. 我把我的Extra,然后分配给一个字符串,而不是我把它解析为一个整数。 These are normal and easy for me and working.
这对我来说很正常,也很容易。
Intent i = getIntent();
String position = i.getStringExtra("POSITION");
int position_to_int = Integer.parseInt(position);
But my problem is about resources. 但我的问题是关于资源。
Simply I want to put an image to my LinearLayout dynamically . 我只想动态地将图像放到LinearLayout上。 I have some country flags and they named in format like
0.gif
, 1.gif
, 2.gif
, 3.gif
... 我有一些国旗,他们的格式如
0.gif
, 1.gif
, 2.gif
, 3.gif
...
My idea is using position
variable's value for this purpose. 我的想法是为此目的使用
position
变量的值。
but when I try to use position_to_int
variable for name of flag, Eclipse returning error normally. 但是当我尝试使用
position_to_int
变量作为标志名时,Eclipse正常返回错误。 Because R.drawble.XXX
values storing in R.java
因为
R.drawble.XXX
值存储在R.java
ImageView imageView = new ImageView(this);
// setting image resource
imageView.setImageResource(R.drawable.position_to_int);
How can I use position_to_int
variable to show an ImageView dynamically? 如何使用
position_to_int
变量动态显示ImageView?
You can't access it directly. 您无法直接访问它。 You'll have to get the resource using its name:
您必须使用其名称获取资源:
private Drawable getDrawableResourceByName(int name) {
String packageName = getPackageName();
int resId = getResources().getIdentifier("character_you_prefixed" + String.valueOf(name), "drawable", packageName);
return getResources().getDrawable(resId);
}
Note that your resource names must begin with a letter, not a number, or else your project will not compile. 请注意,您的资源名称必须以字母开头,而不是数字,否则您的项目将无法编译。 Try adding a character to the beginning of each file name.
尝试在每个文件名的开头添加一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.