Android: Dynamic ImageViews with layout width, height, and margin attributes

I needed to create a dynamic gallery yesterday. I could easily create an ImageView and add it to a container. But it was hard to set layout parameters to the image. I needed it to position it correctly. Most important need was to set its width as MATCH_PARENT. It can be done by setting up a proper LayoutParams object.

Now you need to choose the right LayoutParams class depending on the parent view of Image. I was adding it to a LinearLayout. So my LayoutParams object looked like this:


            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

I also added margins to the LayoutParams object. After that just set it to the ImageView object


lp.setMargins(0, 0, 0,getActivity().getResources().getDimensionPixelSize(R.dimen.gallery_margin));

Here goes the complete function



    private void inflateImage(Photo photo){

        String filename = Photo.PHOTO_PREF + photo.id;

        Log.e(TAG, "photo inlation " + filename);

        try {

            FileInputStream fileInputStream = getActivity().getApplicationContext().openFileInput(filename);

            Drawable drawable = Drawable.createFromStream(fileInputStream, filename);

            ImageView imageView = new ImageView(getActivity());

            imageView.setImageDrawable(drawable);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            lp.setMargins(0, 0, 0,getActivity().getResources().getDimensionPixelSize(R.dimen.gallery_margin));

            imageView.setLayoutParams(lp);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            imageView.setAdjustViewBounds(true);

            productImageContainer.addView(imageView);

            Log.e(TAG, "photo inlation complete " + filename);

        } catch (Exception e){

            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();

            e.printStackTrace();

            Log.e(TAG, "photo inlation failed " + filename +" reason " + e.getMessage());

        }

    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s