我想为自己制作一个ListView,其中的行显示某些产品的名称和价格水平对齐。
我希望价格能够获得所需的宽度,以及在宽度用完时换行的名称。
所以我使用了水平LinearLayout,但是名称和价格重叠。所以我尝试了这个LinearLayout空间分布解决方案,但这样名称和价格都被包装了。
有没有办法实现“拿走你需要的”+“拿走剩下的”分配?
当您知道想要如何准确地划分空间(按比例或等比例)时,LinearLayout 会很好用。
使用
RelativeLayout
可以更好地实现所描述的布局。
注意:您可能需要对您的名称 TextView 使用
minWidth
属性,这样,如果价格文本变得足够长以覆盖整个宽度,名称 TextView 不会被推出屏幕。
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/price"
android:minWidth="100dp"
android:text="Name extra text goes to next line"
android:textColor="@color/black"
android:textSize="28sp" />
<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="Long Price Text Text"
android:textColor="@color/black"
android:textSize="28sp" />
</RelativeLayout>
输出示例:
但是,如果您仍然想使用
LinearLayout
,您可以使用 maxWidth
属性限制名称 TextView 的大小。但在这种情况下,如果价格文本很小,您的名称文本仍将按照您定义的最大宽度进入下一行。但在 RelativeLayout
的情况下就不会发生这种情况。