15

I've got the following problem: I implemented a HorizontalScrollView which contains in one case a LinearLayout and an ImageView. In this case the image is about 50% of the screen width. So I want to center it. Unfortunately the only way I found to center it is, to use layout_gravity="center" on the LinearLayout.

Here's my xml:

<HorizontalScrollView
            android:layout_gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

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

        <ImageView                    
                android:src="@drawable/myImg"
                android:layout_width="wrap_content"
                android:adjustViewBounds="true"
                android:layout_height="150dp"/>

        </LinearLayout>

    </HorizontalScrollView>

But I need to set the layout_gravity programmatically. Does anybody has an idea how I can achieve this or knows a different way? All the things I found via Google are not working for me like this post.

Thanks!

Community
  • 1
  • 1
Ron
  • 22,128
  • 31
  • 108
  • 206

3 Answers3

39

Do somethings like this :

   LayoutParams lp = new LayoutParams();
   lp.gravity= Gravity.CENTER_HORIZONTAL; 
   myImg.setLayoutParams(lp);

UPDATE : Another way to do this :

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.weight = 1.0f;
            params.gravity = Gravity.CENTER;

            imageView.setLayoutParams(params);
Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
  • So, for the gravity value to work, the element must have MATCH_WIDTH set or occupy the full width of its parent. If this is not the case, then it must have a weight value of 100%(which makes its occupy the parent fully), only then does setting gravity work. – somedev Oct 11 '17 at 09:51
8

Put the ImageView in a FrameLayout like this:

Removed extra code

ImageView image = new ImageView(mContext);
image.setLayoutParams(new FrameLayout.LayoutParams(width, height, gravity));

More info here.

ClaireG
  • 1,244
  • 2
  • 11
  • 23
  • 2
    not working... but anyway, why shall i put the imageview inside a `FrameLayout` and put FrameLayout.Params to the imageView and not the parent? – Ron Jul 31 '13 at 14:32
  • 2
    the third parameter is not `gravity` it's `weight`! – Bruce Lee Mar 26 '17 at 11:12
1

I think , this one will work for you

FrameLayout.LayoutParams layoutParams = new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
 layoutParams1.gravity(YourGravity);
yourImage.setLayoutParams(layoutParams);
alp_the_developer
  • 615
  • 1
  • 9
  • 23