Search code examples
androidandroid-imageviewmarginsandroid-image

Issue on image size, while adding it programmatically


I have a little (& bit tricky) problem and could not solve from many hours by myself. The problem scenario is:

I'm adding TextView s (i.e. Titles) and related (click-able) ImageView s programmatically (from database). The margin between them is already very large (I have not added any margin or padding betwwen them). I want to set margin to only 1dp. But I can't.

I used the following code:

LinearLayout linearLayout = (LinearLayout) this.findViewById(R.id.linearLayout);

//No params and margins used for it
TextView tvTitle = new TextView(this); // getting from json (dynamically)
tvTitle.setTextSize(17) ;
tvTitle.setText(title) ;
linearLayout.addView(tvTitle) ;

ImageView image = new ImageView(this) ;
// here getting the image from url

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) ;
params.setMargins(5, 0, 5, 0) ;
image.setLayoutParams( params );
linearLayout.addView(image) ;

As here topMargin and bottomMargin are 0 but when app runs; there is almost 20dp margins above and below the images.

When I increase the margin from 20dp i.e. When I replace any 0 to 30 or 40 then margin increases but when I decrease it up to 5 or 1 or 0 then it does not decrease. It remains near about 20 dp. Anyone having idea about it...


Solution

  • Sounds like the viewbounds on the ImageView are not getting adjusted correctly. Try settings this on your ImageView:

    image.setAdjustViewBounds(true);