如下图,有这样一个需求:

横排的布局,从图上看出一共有四个控件。两个View,两个TextView。整体布局要求显示在页面的右侧;第一个TextView距离第二个棕色View的距离固定,且第一个TextView宽度根据字数自适应宽度(字数越多,宽度越宽。当所有控件填满布局时,这个控件以末尾“...”的形式展示)。

如果将TextView设置成宽度wrap_content时,在字数很长的时候,会将第一个红色的View顶出布局。这个方法不可行。

67dd0ea371d48625ad33779a769fe986.png

最新方案:

使用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 use WRAP_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这两个属性。

老方案:

我用一下方式实现这个布局,供大家参考:

将第一个View和第一个TextView包裹在一个LinearLayout中,让这个LinearLayout的宽度为页面剩余宽度。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐