在 android 中将动态 ImageView 添加到水平滚动视图

Adding Dynamically ImageViews to horizontal scrollview in android

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

Here is my code its working fine but i want it in Horizontal Scroll View

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]

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

或者你可以动态地做如下

在这里你可以做的是在滚动视图中添加线性水平布局说 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);
}
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 );
}