【发布时间】:2019-05-23 05:12:04
【问题描述】:
如何在relative layout中水平等距放置视图?
我想根据添加的视图数量将视图放置在占用相等空间的相对布局中,类似于Linear Layout中的weight
我试过的布局:(三个视图)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<View
android:id="@+id/root"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:background="@android:color/holo_blue_bright"/>-->
<RelativeLayout
android:id="@+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true">
<View
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:background="@android:color/holo_blue_bright"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/middle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/left">
<View
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:background="@android:color/holo_blue_bright"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/middle"
android:layout_alignParentEnd="true">
<View
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:background="@android:color/holo_blue_bright"/>
</RelativeLayout>
</RelativeLayout>
上述布局的问题是前两个视图类似于wrap_content,而第三个视图占据了所有剩余空间。如何让每个视图占据三分之一的水平空间?
注意:
1.请仅在相对布局中提供解决方案,而不是linear layout或constraint layout。
2. 需要的解决方案不要嵌套Linear或其他布局。 (想要平面布局)
【问题讨论】:
-
你为什么要用
RelativeLayout做这个?此处使用的正确组件是ConstraintLayout。当然,从技术上讲,RelativeLayout 可能是可行的,但使用 ConstraintLayout 会容易得多。 -
@BenP。布局是我最初尝试使用约束布局的复杂视图的一部分,但无法使用它来实现。
-
那么我建议您将精力集中在让 ConstraintLayout 正常工作上,而不是尝试使用 RelativeLayout 解决这个问题。
-
@BenP。我已经尝试了几天,并且我还在 SO 中发布了一个问题。我看不到任何进一步的改进,因此尝试了这个。你能帮我解决这个问题吗?问题链接:stackoverflow.com/q/56259274/9636037
-
啊,是的,这个问题看起来也相当复杂。为此,我认为您最好进行自定义绘图而不是尝试构建 ConstraintLayout。
标签: android android-relativelayout