首页 > 解决方案 > 如何将芯片项目的区域(包装区域)限制为 ChipGroup 内的最大 2 行?

问题描述

我正在尝试实现一个带有一些芯片项目的芯片组。到目前为止效果很好。但我的要求是在ChipGroup中以一定数量的行显示这些项目。例如:我的组中有 20 件物品作为筹码,两行之间只有 6/7 件物品。所以,我只想在两行之间展示适合 ChipGroup 的芯片。

目前我得到这个(样本)输出:

现在的情况

我的期望如下:

预期输出

附加查询:

标签: androidkotlinmaterial-designandroid-chips

解决方案


我使用客户视图来制作此功能。

public class AppChipGroup extends ChipGroup {

    private static final int[] MAX_HEIGHT_ATTRS = {android.R.attr.maxHeight};

    private int mMaxHeight = Integer.MAX_VALUE;

    public AppChipGroup(Context context) {
        super(context);
    }

    public AppChipGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AppChipGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, MAX_HEIGHT_ATTRS);
        mMaxHeight = typedArray.getDimensionPixelSize(0, Integer.MAX_VALUE);
        typedArray.recycle();
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = Math.min(getMeasuredHeight(), mMaxHeight);
        setMeasuredDimension(getMeasuredWidth(), height);
    }

}

然后在使用 ChipGroup 时,设置 maxHeight 值。

<packagename.chip.AppChipGroup
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/Widget.MaterialComponents.ChipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="@dimen/search_input_history_max_height"
    app:chipSpacing="@dimen/search_input_history_chip_space" />

或者您可以获取芯片高度并计算max_heightinonMeasure方法并设置测量尺寸。


推荐阅读