在循环中动态创建ImageViews



我已经写了这段代码,加载图像到ImageView小部件:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery);
    i = (ImageView)findViewById(R.id.imageView1);
    new get_image("https://www.google.com/images/srpr/logo4w.png") {
        ImageView imageView1 = new ImageView(GalleryActivity.this);
        ProgressDialog dialog = ProgressDialog.show(GalleryActivity.this, "", "Loading. Please wait...", true);
        protected void onPreExecute(){
             super.onPreExecute();
        }
         protected void onPostExecute(Boolean result) {
             i.setImageBitmap(bitmap); 
         dialog.dismiss();
         }
    }.execute();

}

但是现在,我想加载几个图像。为此,我需要动态创建图像视图,但我不知道如何…

我想在for循环中运行我的代码:

for(int i;i<range;i++){
   //LOAD SEVERAL IMAGES. READ URL FROM AN ARRAY
}

我的主要问题是在一个循环中动态地创建几个imageview

您可以根据需要修改布局,图像资源和图像编号(也可以是动态的)…

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

您可以使用此代码创建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);

其中theLayout是你想要添加图像视图的布局。

要了解更多定制,请查看dev页面,其中列出了所有可能的选项。

如果您的需求显示在列表或Gridview中,那么您应该选择延迟加载列表或网格。

请点击以下链接。

https://github.com/thest1/LazyList

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

试试这个

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

最新更新