自定义Linearlayout

有一个需求。水平linearlayout,里有一个项目名称,右边紧跟项目属性。有一个问题出来了,当项目名称太长,项目属性会挤掉。

所以当项目名称太长的时候,用省略号表示,项目属性居右。git里边有两种实现方式。推荐自定义Linearlayout。记得点STAR.

https://github.com/xiayu98020214/MyLinearlayout

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以创建一个自定义LinearLayout并覆盖onMeasure方法来实现宽度可变的效果。在这个方法中,您可以通过调整子视图的大小和位置来改变LinearLayout的大小。 以下是一个示例代码: ```java public class CustomLinearLayout extends LinearLayout { private int mMaxWidth = Integer.MAX_VALUE; // 默认最大宽度 public CustomLinearLayout(Context context) { super(context); } public CustomLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public void setMaxWidth(int maxWidth) { mMaxWidth = maxWidth; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = 0, measuredHeight = 0, childWidth, childHeight; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); // 测量子视图 measureChildren(widthMeasureSpec, heightMeasureSpec); // 计算子视图占用的空间 int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); MarginLayoutParams params = (MarginLayoutParams) child.getLayoutParams(); childWidth = child.getMeasuredWidth() + params.leftMargin + params.rightMargin; childHeight = child.getMeasuredHeight() + params.topMargin + params.bottomMargin; measuredWidth += childWidth; measuredHeight = Math.max(measuredHeight, childHeight); } // 调整LinearLayout的大小 if (widthMode == MeasureSpec.EXACTLY) { measuredWidth = Math.min(measuredWidth, MeasureSpec.getSize(widthMeasureSpec)); } measuredWidth = Math.min(measuredWidth, mMaxWidth); setMeasuredDimension(measuredWidth, measuredHeight); } } ``` 您可以在布局文件中使用CustomLinearLayout并为其设置最大宽度: ```xml <com.example.CustomLinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" app:maxWidth="500dp"> <!-- 添加子视图 --> </com.example.CustomLinearLayout> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值