2

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?

4

2 回答 2

5

尝试设置布局权重:

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

这(假设您的方向是垂直的)将允许您的视图填充线性布局中的剩余空间,并且应该水平居中。

我认为没有办法让视图子项小于包含它的 LinearLayout 单元格。如果视图小于其“单元格”,则 LinearLayout 将缩小以适应它。如果布局权重导致“单元格”增长,那么包含的视图也会增长。

如果您真的希望视图小于其“单元格”并居中,请将其包装在 FrameLayout 中。然后,您将能够随心所欲地使用重心。layout_width="fill_parent" 在xml中(我知道你不能直接使用这个,但是这样解释更容易):

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

未标记的布局属性是“fill_parent”。

于 2011-03-15T05:43:42.243 回答
1

看看这个:http ://thinkandroid.wordpress.com/2010/01/14/how-to-position-views-properly-in-layouts/

基本上, android:gravity 影响 View 中的位置,而 android:layout_gravity 相对于其父项定位 View。所以你需要使用布局重力来移动整个 View。

于 2011-03-15T05:41:58.970 回答