Question

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.

Was it helpful?

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

OTHER TIPS

Is there a need to do layout in your code? If number of Images you want to display is always three, just create an XML layout file and then dynamically set image for them.

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" 
        android:layout_margin="5dp"/>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" 
        android:layout_margin="5dp"/>

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" 
        android:layout_margin="5dp"/>

</LinearLayout>

And then in your code:

ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
iv1.setImageBitmap(YOUR_BITMAP);
// ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top