我有一个TextView和一个正方形ImageView,我想在水平线性布局中显示它们。每个应该占据父视图宽度的一半,并且高度应适合内容(即图片)。文本应该垂直居中。
额外的限制是图像不应超过给定的maxWidth(= maxHeight),超出的宽度应该提供给TextView。显然,这与上面的50/50规则冲突。是否有一种方法可以优先考虑约束条件,即允许图像占据空间的一半,除非它超出了给定的大小? 这些是我尝试过的布局:
第一个布局能够很好地将左侧部分拉伸到可用空间。但是,由于图像的layout_weight未指定(如下图所示),因此图像占据了超过一半的宽度。
额外的限制是图像不应超过给定的maxWidth(= maxHeight),超出的宽度应该提供给TextView。显然,这与上面的50/50规则冲突。是否有一种方法可以优先考虑约束条件,即允许图像占据空间的一半,除非它超出了给定的大小? 这些是我尝试过的布局:
第一个布局能够很好地将左侧部分拉伸到可用空间。但是,由于图像的layout_weight未指定(如下图所示),因此图像占据了超过一半的宽度。
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some text."/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="200dp"
android:adjustViewBounds="true"
android:src="@drawable/image" />
</LinearLayout>
当我给ImageView
添加layout_weight
属性时,它总是占据一半的宽度并忽略maxWidth
属性(见下图)。 <ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:maxWidth="200dp"
android:adjustViewBounds="true"
android:src="@drawable/image" />
将ImageView
包含在另一个LinearLayout
中可以再次启用maxWidth
,但是包含的LinearLayout
仍然占用可用空间的一半(请参见下面的图像)。
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:maxWidth="200dp"
android:adjustViewBounds="true"
android:src="@drawable/image" />
</LinearLayout>
我发现类似情况的另一个选择是使用RelativeLayout
,并将一个不可见视图作为中心分隔器,但这将锁定分割线为50/50(或分隔器所在位置)。
TextView
填充另一个屏幕很容易,但是当每个View
(TextView 和 ImageView)占据父级宽度的一半时,就会出现冲突条件,这使得情况变得困难。 - AL.