我想做一些像这样的布局。
- A 是消息框。
- B 是个人资料照片
- C 是一个描述,应位于 A 的右侧并与 B 垂直居中
一些条件是: - A 应位于 B 上方且与 B 水平居中 - A 的宽度始终大于 B - C 的高度始终小于 B - B和C之间不应有间隙
如果我将所有三个对象放入一个容器中,我找不到将 A 和 B 中心水平对齐的方法。 (layout_below
将 B 放在 A 下方,但左对齐)
我也尝试制作一个包含A和B的容器,但如果是这样,我不能将C放在B后面(这会导致B和C之间有间隙,因为A的宽度大于B)。
有什么方法可以只使用 XML 布局来存档它吗?
最佳答案
我个人认为,如果没有额外的代码,就不可能达到您想要的效果。
我可以通过在 View B 中设置 android:layout_marginLeft
来达到你想要的效果。为了保持 View 以 A 为中心,你必须始终通过以下公式设置边距:
android:layout_marginLeft = ( (width_from_A / 4) + (width_from_B / 2) )
在下面的示例中,width_from_A == 200dp
和 width_from_B == 50dp
所以,
android:layout_marginLeft = ( (200 / 4) + (50 / 2) )
android:layout_marginLeft = ( 50 + 25 )
android:layout_marginLeft = 75dp
Java
如果您的 View 并不总是具有相同的宽度,您可以通过 Java 代码动态设置边距。这应该可行,因为在您的 Activity 中,在向用户显示布局之前,您可以从 A 获取宽度,从 B 获取宽度,并手动设置 B 的 LeftMarging。
@Override
protected void onResume() {
int widthA = findViewById(R.id.viewA).getLayoutParams().width;
int widthB = findViewById(R.id.viewB).getLayoutParams().width;
// THIS LINE JUST WORK FOR API>17
((RelativeLayout.LayoutParams)findViewById(R.id.viewB).getLayoutParams()).setMarginStart(widthA/4 + widthB/2);
//FOR ANY API
((RelativeLayout.LayoutParams)findViewById(R.id.viewB).getLayoutParams()).setMargins(widthA/4 + widthB/2,0,0,0);
super.onResume();
}
布局
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/viewA"
android:layout_width="200dp"
android:layout_height="50dp"
android:gravity="center"
android:text="A"
android:background="@android:color/holo_blue_dark"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/viewA">
<TextView
android:id="@+id/viewB"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="B"
android:layout_marginLeft="75dp"
android:background="@android:color/holo_green_dark"/>
<TextView
android:id="@+id/viewC"
android:layout_width="150dp"
android:layout_height="50dp"
android:gravity="center"
android:text="C"
android:layout_toRightOf="@+id/viewB"
android:background="@android:color/holo_red_dark"/>
</RelativeLayout>
</RelativeLayout>
结果
关于Android 相对布局中心水平与另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505585/