动态ImageViews添加到android中的水平scrollview

时间:2015-05-15 05:39:34

标签: android imageview horizontalscrollview dynamically-generated

我试图通过字符串动态显示图像作为ID,并希望在水平滚动视图中显示它,因为我有13张无法在屏幕上显示的卡

enter image description here

  

这是我的代码工作正常,但我希望它在水平滚动视图

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
        ImageView im = (ImageView) findViewById(resID);
        Context context = im.getContext();
        int id = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName());


        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(im.getLayoutParams());

        lp.setMargins(counter * 43, 0, 0, 0);//left,right,top,bottom
        im.setLayoutParams(lp);
        im.setImageResource(id);
        im.setOnClickListener(this);
        counter++;

    }

    mp = MediaPlayer.create(getApplicationContext(), R.raw.clicksound);
}![enter image description here][2]

2 个答案:

答案 0 :(得分:2)

根据您的要求,我建议您使用带有库的RecyclerView,您必须添加并使用水平方向的RecyclerView参考下面的链接。 https://developer.android.com/training/material/lists-cards.html

或者您可以动态执行以下操作

这里你可以做什么在scrollview里面添加线性水平布局说id是imgcontainer然后你可以做的是

动态创建图像视图并添加到线性布局。

for(int i=0;i<10;i++)
{
  //create imageview here and setbg
   ImageView imageView = new ImageView(this);
   imageView.setImageResource(R.drawable.ic_launcher);
  ((LinearLayout) findViewById(R.id.imgcontainer)).addView(
                    imageView, i);
}

答案 1 :(得分:0)

int[] image_array = new int[]{R.drawable.image1, R.drawable.image2, ... R.drawable.image10};
LinearLayout ll = (LinearLayout) findViewById (R.id.ll_images);
for (int i=0 ; i<10; i++){
   ImageView img = new ImageView (this);
   img .setBackgroundResource (image_array [i]);
   ll .addView(img );
}