【发布时间】:2018-06-20 14:27:06
【问题描述】:
上下文
我有一个带有两个视图的 FrameLayout:一个 ImageButton 和一个 TextView。
我想要什么:
- ImageButton 应包装其内容
- ImageButton 位于布局的左侧
- TextView 位于布局的中心
- TextView 应该包装它的内容,但不能与 ImageButton 重叠,就像在这个例子中Overlapping text
我的第一个解决方案
使用RelativeLayout 避免重叠。
<RelativeLayout
android:id="@+id/dialog_header"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/dialog_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_padding="20dp"
android:src="@drawable/btn_close"
android:layout_alignParentStart="true"/>
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some text"
android:textSize="17sp"
android:textAlignment="center"
android:layout_toEndOf="@id/dialog_close"
android:layout_centerVertical="true"/>
</RelativeLayout>
但是现在,TextView 不在布局中居中:而是在 ImageButton 和 Parent 的末尾之间居中。 Text not centered
而且我无法添加按钮大小的边距,因为我真的不知道它的大小。
我的第二个解决方案
保留RelativeLayout,并添加一个不可见的假按钮(与第一个相同的图片,因此大小相同)。并将 TextView 在两个按钮之间居中。
<RelativeLayout
android:id="@+id/dialog_header"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/dialog_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_padding="20dp"
android:src="@drawable/btn_close"
android:layout_alignParentStart="true"/>
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some text"
android:textSize="17sp"
android:textAlignment="center"
android:layout_toEndOf="@id/dialog_close"
android:layout_toStartOf="@id/dialog_margin"
android:layout_centerVertical="true"/>
<ImageButton
android:id="@+id/dialog_margin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_padding="20dp"
android:src="@drawable/btn_close"
android:layout_alignParentEnd="true"
android:visibility="invisible"/>
</RelativeLayout>
这导致了我想要的行为: Result with fake button
但我觉得使用假按钮不是正确的做法。
是否有另一种解决方案可以使视图居中并避免重叠,而不是使用不可见的假按钮技巧?
如果能带来解决方案,我可以轻松使用另一种布局(约束、线性...)
感谢您的回答!
【问题讨论】:
-
我不明白您希望它如何精确对齐,但如果您希望 1 个视图居中,另一个视图与该视图对齐而不重叠,您应该使用
ConstraintLayout跨度> -
@Sander 我编辑我的问题以使对齐更加清晰。并且看不到如何使用 ConstraintLayout 做到这一点,但是如果您有答案,请赐教!
-
如果你想水平排列它们,你可以将它们包含在
LinearLayout中,然后设置textView的layout_gravity="center"的属性 -
我认为您应该为您的 ImageView 设置一个固定大小,因为允许任何大小都可能是危险的(您最终可能没有足够的空间来显示 TextView,尤其是在小型设备上)。像这样,你可以为你的 TextView 设置一个右边距,因为你知道 ImageView 的大小
-
@Eselfar:是的,我不认为拥有不固定尺寸的图片会成为问题。考虑到这一点,文本应该很容易居中!
标签: android xml android-layout