Android - 滚动到ChipGroup中选定的子项位置

3
我将尝试创建一个包含4个Chips的水平滚动ChipGroup的活动。
该活动将使用ChipGroup作为API调用的过滤器,并且可以通过Extras告知用户选择的芯片。
目前,我是这样做的:
chipScroll.postDelayed(() -> {
                chipScroll.smoothScrollBy(800, 0);
            },100);

但这是一个很巧妙的解决方案,与我想要实现的目标不太一样。是否有其他方法在水平滚动 ChipGroup 中滚动到所选的芯片?
编辑:
我考虑过尝试迭代获取 ChipGroup 中的所有芯片并匹配其 ID。但这也是一个巧妙的方法。我希望能够做到类似于 spinnerAdapter.getItem(spinner.getSelectedItemPosition) 这样的东西。
3个回答

6
我在 这里 找到了答案。
我忘记了 ChipGroup 基本上只是一个ViewGroup,而HorizontalScrollView 只是用于它的滚动目的的额外选项。
我可以做像下面这样的事情:
chipGroup.post(() -> {
    Chip chipByTag = chipGroup.findViewWithTag(filterModel.getComplaint_status());
    chipGroup.check(chipByTag.getId());
    chipScroll.smoothScrollTo(chipByTag.getLeft() - chipByTag.getPaddingLeft(), chipByTag.getTop());
});

如果在onCreate中执行此操作,将会崩溃,因为Tag尚未分配,并且我正在使用XML中的DataBinding进行标记(如有错误请指出),因此我们应该在.post()可运行程序中执行。


1

您需要使用HorizontalScrollView包装ChipGroup,并在芯片选择后调用此扩展函数:

inline fun <reified T : View> HorizontalScrollView.scrollToPosition(
    tag: String?,
) {
    val view = findViewWithTag<T>(tag) ?: return
    val leftEdgePx = view.left
    val screenCenterPx = Resources.getSystem().displayMetrics.widthPixels / 2
    val scrollPx = if (leftEdgePx < screenCenterPx) 0
    else leftEdgePx - screenCenterPx + view.width / 2
    this.post {
        this.smoothScrollTo(scrollPx, view.top)
    }
}

这将始终显示所选芯片在屏幕中央(如果可能的话)。

1
对于Kotlin:使用@Kevin Murvie的答案。
binding.layoutChipChoiceProducts.chipGroupDrinksChoice.post {
        val chip =
            binding.layoutChipChoiceProducts.chipGroupDrinksChoice.findViewWithTag<Chip>(tag)
        binding.layoutChipChoiceProducts.scrollLayoutChip.scrollTo(
            chip.left - chip.paddingLeft, chip.top
        )
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接