1

I want to create a HorizontalScrollView which reads the images from drawable folder. The name of the images are "image1" "image2" ... "image20". I don´t know how I can use the numbers to read them. Here is what I have:

protected void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   LinearLayout sv = (LinearLayout) findViewById (R.id.images);
   for (int i=1 ; i<20; i++){
       ImageView iv = new ImageView (this);
       iv.setBackgroundResource (R.drawable.image1);
       sv.addView(iv);
   }
}
4

3 回答 3

3

你可以通过两种方式做到这一点。

第一个是使用您要使用的图像的 id 创建数组,在您的for循环中,只需将图像添加到您的布局中:

int[] images = new int[]{R.drawable.image1, R.drawable.image2, ... R.drawable.image20};
LinearLayout sv = (LinearLayout) findViewById (R.id.images);
for (int i=0 ; i<20; i++){
   ImageView iv = new ImageView (this);
   iv.setBackgroundResource (images[i]);
   sv.addView(iv);
}

或者第二种方式,你可以创建类似这样的东西:

 for (int i=1 ; i<=20; i++){
   String uri = "drawable/image"+i;
   // int imageResource = R.drawable.image1;
   int imageResource = getResources().getIdentifier(uri, null, getPackageName());

   ImageView iv = new ImageView (this);
   iv.setBackgroundResource (imageResource);
   sv.addView(iv);
 }

我没有测试代码,但我认为它们应该可以工作。

于 2013-07-09T22:43:48.053 回答
1

如果您希望在drawables没有数组列表的情况下使用,可以这样做:

getResources().getIdentifier("Name of the Drawable", "drawable", "Your Package Name");

所以你的代码将是:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    LinearLayout sv = (LinearLayout) findViewById (R.id.images);

    for (int i=1 ; i<20; i++){
        ImageView iv = new ImageView (this);
        int myImage = getResources().getIdentifier("image"+i, "drawable", "Your Package Name");
        iv.setBackgroundResource(myImage);
        sv.addView(iv);
    }

}
于 2013-07-09T22:50:34.983 回答
0

很多像这样的例子展示了首先建立你的图像列表。然后您可以使用您的代码并遍历列表。

所以像

List<Drawable> imagesToAdd = Arrays.asList(R.drawable.image1,R.drawable.image2, .... R.drawable.image20);

然后你甚至可以使用 foreach 循环来遍历它。

for (Drawable image in imageToAdd) {
  etc...
}
于 2013-07-09T22:39:35.920 回答