将一个视图的垂直中心与另一个视图的顶部对齐

3

看起来很简单,但我似乎无法想出如何生成能实现以下结果的xml:(stackoverflow上有很多有趣的内容,但令人惊讶的是,我没有找到任何回答这个问题的内容)

enter image description here

黑色视图是外框,蓝色视图对齐底部,红色视图的垂直中心对齐蓝色视图的顶部。
约束条件:
  • 不要假设红色视图有固定大小(计算偏移边距的一半),
  • 不要使用编程方式实现,使用xml规则。
编辑:修复了混乱的描述并添加了约束条件。

水平居中是什么意思?两个视图似乎覆盖了根视图的整个宽度。您能在图像上放置一个标记显示对齐方式吗? - tasomaniac
@tasomaniac 抱歉,我修复了混乱的描述和图片。 - Gurg Hackpof
我会考虑如何在xml中实现这个。通过编程很容易实现。将视图放在另一个视图的顶部,并给出负底边距,高度为一半即可。 - tasomaniac
仅使用 XML 是不能实现它的。 - tiny sunlight
@tinysunlight 如果您能稍微解释一下,我就准备接受这个答案了。 - Gurg Hackpof
显示剩余2条评论
2个回答

1
如果您无法确定固定高度,则需要在运行时确定边距,当高度确定时。否则,您将硬编码底部边距为布局高度(蓝色布局的一半负值)。我提供了两个嵌套布局,供您在主活动布局中使用。
在这种特殊情况下,我使用了一个按钮来测试应用程序,您可以以任何方式实现它。您向xml添加布局的顺序将影响它们的可见性。将要置于顶部的布局放在最后是很重要的。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ../..
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/black"
            tools:showIn="@layout/activity_main">

    <RelativeLayout android:id="@+id/l1"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/holo_blue_light"/>

    <RelativeLayout android:id="@+id/l2"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_above="@+id/l1"
        android:background="@android:color/holo_red_light"/>
</RelativeLayout>

我从这篇答案中借鉴了一种方法:

public void setMargin(View view) {
    if (relativeLayout
            .getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) relativeLayout
                        .getLayoutParams();
        int margin = relativeLayout.getHeight() / 2;
        marginLayoutParams.setMargins(20, 0, 0, -margin);
        relativeLayout.requestLayout();
    }
}

enter image description here

为了演示,我在两个布局的两侧添加了边距,这样您就可以看到它们重叠的位置。

0

如果浮动视图具有固定大小。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/a"
        android:layout_alignParentBottom="true"
        android:background="#44bb11"
        android:layout_width="match_parent"
        android:layout_height="100dp" />
    <ImageView
        android:layout_marginBottom="-40dp"
        android:layout_above="@+id/a"
        android:id="@+id/c"
        android:background="#45000000"
        android:layout_width="match_parent"
        android:layout_height="80dp" />
</RelativeLayout>

确实,在XML中硬编码一个大小可能会起作用,但我排除了这种可能性。(在描述中添加了约束条件) - Gurg Hackpof

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接