Create ImageViews dynamically inside a loop

房东的猫 提交于 2019-12-02 23:42:58
Hussain Akhtar Wahid 'Ghouri'

you can modify the layout , image resource and no of images (may be dynamic as well) according to your requirement...

LinearLayout layout = (LinearLayout)findViewById(R.id.imageLayout);
for(int i=0;i<10;i++)
{
    ImageView image = new ImageView(this);
    image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80,60));
    image.setMaxHeight(20);
    image.setMaxWidth(20);

    // Adds the view to the layout
    layout.addView(image);
}

You can use this code to create ImageViews

ImageView image = new ImageView(this);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
image.setLayoutParams(vp);
image.setMaxHeight(50);
image.setMaxWidth(50);
// other image settings
image.setImageDrawable(drawable);
theLayout.addView(image);

where theLayout is the layout you want to add your image views to.

For more customization check out the dev page, where all the possible options are listed.

If your requirement is show in List or Gridview then you should go for Lazy Loading List or grid.

Please go through the below link.

https://github.com/thest1/LazyList

https://github.com/abscondment/lazy-gallery

Try this

 rootLayout = (LinearLayout) view1.findViewById(R.id.linearLayout1);

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER_VERTICAL;

    params.setMargins(0, 0, 60, 0);


    for(int x=0;x<2;x++) {
        ImageView image = new ImageView(getActivity());

        image.setBackgroundResource(R.drawable.ic_swimming);
        rootLayout.addView(image);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!