RecycleView的Item文字超过边界

390 阅读1分钟

使用RecycleView,可能遇到Item的文字描述超过其边界的情况,当Content111111是从Item的中间往后展示的,要再遇到多语言翻译...... image.png

可以使用LinearLayoutManager的翻转属性 rv.layoutManager = LinearLayoutManager( requireContext(), LinearLayoutManager.HORIZONTAL, true )

并配合rightSpacing属性

rv.addItemDecoration(SpacingItemDecoration().apply { rightSpacing = CommonUtils.dp2px(context, -100f) })

注意,adpter的xml中Item的宽要比预设的多100dp,为了正常展示文字

最后,adapter的list顺序也要翻转:

val list = listof("Content4", "Content3333", "Content2", "Content111111") 

最最后,要用背景图的话,记得背景图透明化处理。 SpacingItemDecoration的代码如下:

open class SpacingItemDecoration : RecyclerView.ItemDecoration() {
    var leftSpacing:Int = 0
    var rightSpacing:Int = 0
    var topSpacing:Int = 0
    var bottomSpacing:Int = 0
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        if (leftSpacing != 0) {
            outRect.left = leftSpacing
        }
        if (rightSpacing != 0) {
            outRect.right = rightSpacing
        }
        if (topSpacing != 0) {
            outRect.top = topSpacing
        }
        if (bottomSpacing != 0) {
            outRect.bottom = bottomSpacing
        }
    }
}