【问题标题】:Add images to a HorizontalScrollView将图像添加到 Horizo​​ntalScrollView
【发布时间】:2013-07-09 22:32:25
【问题描述】:

我想创建一个从可绘制文件夹中读取图像的 Horizo​​ntalScrollView。图像的名称是“image1”“image2”...“image20”。我不知道如何使用这些数字来阅读它们。这是我所拥有的:

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);
   }
}

【问题讨论】:

    标签: android image add horizontalscrollview


    【解决方案1】:

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

    第一个是使用您要使用的图像 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);
     }
    

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

    【讨论】:

    • 非常感谢您的帮助,非常有用
    【解决方案2】:

    如果你想在没有数组列表的情况下使用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);
        }
    
    }
    

    【讨论】:

      【解决方案3】:

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

      类似

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

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

      for (Drawable image in imageToAdd) {
        etc...
      }
      

      【讨论】:

      • 这实际上是不正确的,因为您想在那里实例化一个可绘制元素列表,但您实际上是在添加可绘制元素的资源 ID。