Search code examples
androidandroid-layouttextviewandroid-layout-weight

Weight setting for a set of three image in a linear horizontal layout


I've a single vertical linear layout with a scrollview inside it.

Programmatically I'm adding some thing inside it

  • A TextView, and it's OK: I'm able to center it using

    LayoutParams params = new LinearLayout.LayoutParams (
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT
    );
    
    ...
    
    monthNameTextView.setLayoutParams(params);
    monthNameTextView.setGravity(Gravity.CENTER_HORIZONTAL);
    
  • Then I add a horizontal LinearLayout. It's OK

    gallery = new LinearLayout(this);
    
    gallery.setOrientation(LinearLayout.HORIZONTAL);
    gallery.setGravity(Gravity.CENTER_HORIZONTAL);
    gallery.setLayoutParams(params);
    
  • Then I add 3 ImageView loading images froms disk

    Bitmap myJpg = BitmapFactory.decodeFile(imgFile.getAbsolutePath());  
    ImageView cover = new ImageView(this);
    cover.setImageBitmap(myJpg);
    gallery.addView(cover);
    

Images are loaded, are three, and are centered into linear layout.

The problem is that there is no spacing from one image the the following one.

I'm new and I'm trying to understand difference from layout_weight and weight, and I'm here to ask you how to set these parameters programmatically to have a simple centered set of three images with 'some' spacing beetween each of them.


Solution

  • Change your code for adding ImageViews to this:

    Bitmap myJpg = BitmapFactory.decodeFile(imgFile.getAbsolutePath());  
    ImageView cover = new ImageView(this);
    cover.setImageBitmap(myJpg);
    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    llp.setMargins(YOUR_DESIRED_SPACE_VALUE, 0, 0, 0); // 4 margin values for Top/Left/Right/Bottom
    gallery.addView(cover, llp);