如下图,有这样一个需求:
横排的布局,从图上看出一共有四个控件。两个View,两个TextView。整体布局要求显示在页面的右侧;第一个TextView距离第二个棕色View的距离固定,且第一个TextView宽度根据字数自适应宽度(字数越多,宽度越宽。当所有控件填满布局时,这个控件以末尾“...”的形式展示)。
如果将TextView设置成宽度wrap_content时,在字数很长的时候,会将第一个红色的View顶出布局。这个方法不可行。
最新方案:
使用ConstraintLayout,设置子布局的 app:layout_constrainedWidth 属性进行限制。
参考文章:https://www.jianshu.com/p/a74557359882
Android refrence 官方解释:
WRAP_CONTENT : enforcing constraints (Added in 1.1)
If a dimension is set to
WRAP_CONTENT
, in versions before 1.1 they will be treated as a literal dimension -- meaning, constraints will not limit the resulting dimension. While in general this is enough (and faster), in some situations, you might want to useWRAP_CONTENT
, yet keep enforcing constraints to limit the resulting dimension. In that case, you can add one of the corresponding attribute:
app:layout_constrainedWidth=”true|false”
app:layout_constrainedHeight=”true|false”
从上面可以了解到:在1.1版本之后,如果想设置ConstraintLayout的子控件宽度为wrap_content,又想限制最后结果宽度可以使用
layout_constrainedWidth和layout_constrainedHeight这两个属性。
老方案:
我用一下方式实现这个布局,供大家参考:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical|end"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center_vertical|end"
android:layout_height="match_parent">
<View
android:id="@+id/v_v1"
android:layout_width="11dp"
android:layout_height="11dp"
android:layout_marginRight="2dp"
android:background="#ED1C24" />
<TextView
android:id="@+id/tv_tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="14dp"
android:ellipsize="end"
android:singleLine="true"
android:text="很长很长很长很长名字的队伍"
android:textColor="#FF909090"
android:textSize="12sp" />
</LinearLayout>
<View
android:id="@+id/v_v2"
android:layout_width="11dp"
android:layout_height="11dp"
android:layout_marginRight="2dp"
android:background="#B97A57" />
<TextView
android:id="@+id/tv_tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="22dp"
android:singleLine="true"
android:text="第二支队伍"
android:textSize="12sp" />
</LinearLayout>
将第一个View和第一个TextView包裹在一个LinearLayout中,让这个LinearLayout的宽度为页面剩余宽度。