繁体   English   中英

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

[英]Android - How do I position views in an offset relative to the center/top/bottom (etc.) of their parent?

我有一个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像素下)中心)?

必要布局的示意图

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

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

在将它应用于textView ,但这不起作用。

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

在不使用xmls的情况下,在代码中实现此功能非常重要。

谢谢!

你有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!"/>

我今晚刚刚开始安装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美分!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM