我有一个 TextView
和一个正方形ImageView
我想以水平线性布局显示。每个都应该占据父 View 宽度的一半,高度应该适合内容(即图像)。文本应垂直居中。
额外的限制是图像不应超过给定的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>
当我添加 layout_weight
时到 ImageView
它总是占用宽度的一半并忽略 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>
我为 similar scenarios 找到的另一个选项是使用RelativeLayout
以不可见的 View 作为中心分隔线,但将分隔锁定为 50/50(或放置分隔线的任何位置)。
最佳答案
好的,继续并发布我创建的 xml,它非常简单,它满足您的大部分条件。我遇到的一件事是每个 View 占用父 View 宽度的一半.希望这仍能以某种方式帮助您。
sample_layout.xml
<?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="wrap_content"
android:layout_margin="2dp"
android:background="@android:color/darker_gray">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/img_sample"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="2dp"
android:layout_toLeftOf="@id/img_sample"
android:background="@color/colorPrimary"
android:gravity="center_vertical"
android:text="Some text." />
<ImageView
android:id="@id/img_sample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="2dp"
android:adjustViewBounds="true"
android:maxWidth="200dp"
android:src="@drawable/sample_img" />
</RelativeLayout>
如果您弄清楚如何处理每个的一半,请在这里发表评论,了解它以供将来使用会很高兴。 :)
PS:您是否考虑过以编程方式完成每个的一半?就像检查 LayoutParams
然后动态设置 weightSum
和 layout_weight
一样。
从这个 link 中检索到的示例图像
关于android - 具有 `layout_weight` 和 `maxWidth` 的灵活水平布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36034364/