Question

I've been trying to center this custom view I have inside this other custom View that extends LinearLayout. This all needs to be done via code because it's all done at runtime.

I've tried the standard approach with setting the gravity:

this.setGravity(Gravity.CENTER);

That was done inside of my class that extends LinearLayout.

I've also tried the LayoutParams method:

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    block.setLayoutParams(params);
    this.addView(block);

This was done in the place where I add the block to the view (as you can see).

Both methods resulted in the block still being aligned in the upper-left hand corner of my view. What are my other options or, more importantly, what in the world am I doing wrong?

Was it helpful?

Solution

Try also setting the layout weight:

LinearLayout.LayoutParams params =
    new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
params.weight = 1;
this.addView(block, params);

This (assuming your orientation is vertical) will allow your view to fill the remaining space in the linear layout and should center it horizontally.

I don't think there is a way to have a view child that is smaller than the LinearLayout cell that contains it. If the view is smaller than its "cell" then the LinearLayout will shrink to accomodate it. If the layout weight causes the "cell" to grow, then the contained view will grow as well.

If you really want the view to be smaller than its "cell" and centered, wrap it in a FrameLayout. Then you will be able to use a center gravity to your heart's content. layout_width="fill_parent" In xml (I know you can't use this directly, but it's easier to explain this way):

<LinearLayout orientation="vertical">
    <FrameLayout layout_weight="1" layout_height="wrap_content">
        <View layout_gravity="center" layout_{width,height}="wrap_content"/>
    </FrameLayout>
        ... other views ...
</LinearLayout>

Unmarked layout attributes are "fill_parent".

OTHER TIPS

Take a look at this: http://thinkandroid.wordpress.com/2010/01/14/how-to-position-views-properly-in-layouts/

Basically, android:gravity affects positions things within a View, whereas android:layout_gravity positions a View relative to its parents. So you need to use layout gravity to move the whole View.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top