Android - 如何将视图定位在相对于其父级的中心/顶部/底部(等)的偏移量中?

时间:2011-10-25 10:20:53

标签: android android-layout

我有一个RelativeLayout,其视图相对于它(它们的父级)对齐,使用(例如):

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
textView.setLayoutParams(layoutParams);

现在我想知道,我如何相对于其父级的底部定位视图,但是在偏移处(例如,底部上方100像素,左侧20像素等),或者与中心类似(中心下30个像素?

schematic image of the necessary layout

我已尝试设置视图的边距(例如):

layoutParams.setMargins(140, 0, 0, 0);

在将其应用于textView之前,但这不起作用。

这似乎是一种非常有用的方法来对齐各种屏幕尺寸的视图。

对我来说,在不使用xmls的情况下在代码中实现这一点非常重要。

谢谢!

2 个答案:

答案 0 :(得分:59)

你有2种方法,简单就是使用位于中心的锚空视图

<View
    android:id="@+id/anchor"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_centerInParent="true" />

<TextView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@id/anchor"
    android:layout_marginBottom="20dp"
    android:text="hello world!"/>

或者你可以将视图居中并使用pading por定位(你必须加倍使用的填充因为它溢出屏幕中心以下)

 <TextView
     android:id="@+id/imageView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerInParent="true"
     android:paddingBottom="40dp"
     android:text="hello world!"/>

答案 1 :(得分:0)

我今晚刚刚开始进行Android编程,所以这可能是旧的或者是个坏主意...但我正在修补上述答案并发现将元素定位在我的其他元素下方导致问题 - 填充是否会在方式或东西。这就是我最终做的事情。

使用锚技术,我还给锚一个高度(你需要的两倍),然后将我的元素与顶部对齐。这样它就会在视图中间减去锚点高度的一半!

<View
    android:id="@+id/anchor"
    android:layout_width="0dp"
    android:layout_height="200dp"
    android:layout_centerInParent="true" />

<TextView
    android:id="@+id/heading"
    android:text="@string/heading"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:layout_alignTop="@id/anchor"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/subheading"
    android:text="@string/subheading"
    android:textColor="@android:color/white"
    android:textSize="12sp"
    android:layout_below="@+id/heading"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

另一个答案帮了很多,但我只是想给我2美分!