【发布时间】:2015-11-16 13:36:34
【问题描述】:
我正在尝试编写这样的代码:我有一个字符串,如果字符串是“堆栈”,我想打印 s.gif、t.gif、a.gif、c.gif 和 k.gif。 这是我写的代码:
String myString = "stack";
for(int i = 0; i < myString.length(); i++)
{
String source= null;
if(myString .charAt(i) == 'a')
{
source = "R.drawable.folder.a.gif";
}
else if (myString .charAt(i) == 'b')
{
source = "R.drawable.folder.b.gif";
}
...//it goes until z
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.MATCH_PARENT));
ImageView imageView = new ImageView(this);
imageView.setImageResource();// I don't know what to write here
imageView.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
setContentView(linearLayout);
}
我要做的是设置源字符串并将其提供给 setImageResource(),但我失败了。你能告诉我如何修复这个代码吗?谢谢。
【问题讨论】:
-
如果你知道资源的路径(
R.drawable部分)为什么不直接设置一个int引用它呢?你为什么要硬编码一个字符串呢? -
@TomG 你能举个例子解释一下吗?谢谢。
-
将
String source = null更改为int source = -1并在 if/else 块中设置source = R.drawable.a。然后像往常一样将source传递给ImageView。 -
旁注,如果您有文件
res/drawable/folder/a.gif:子文件夹are not supported for android resources。您的图像可能根本不包含在应用的资源R中。
标签: android