Android recyclerview删除所有项目装饰器

时间:2017-06-11 05:33:44

标签: android android-recyclerview

我这样做了:

dividerItemDecoration = new DividerItemDecoration(
        recyclerView.getContext(),
        DividerItemDecoration.VERTICAL
    );
recyclerView.addItemDecoration(dividerItemDecoration);

然后我改变设备方向,所以现在我没有dividerItemDecoration,我想从recyclerView删除分隔符。有可能吗?

7 个答案:

答案 0 :(得分:12)

你可以这样做:

while (recyclerView.getItemDecorationCount() > 0) {
    recyclerView.removeItemDecorationAt(0);
}

答案 1 :(得分:8)

要删除ItemDecoration,您需要使用 removeItemDecoration 。对于您的情况,代码将是:

recyclerView.removeItemDecoration(dividerItemDecoration);

答案 2 :(得分:1)

试试这个,对我有用:

RecyclerView.ItemDecoration itemDecoration;

while (recyclerView.getItemDecorationCount() > 0 
        &&(itemDecoration = recyclerView.getItemDecorationAt(0)) != null) {
                    recyclerView.removeItemDecoration(itemDecoration);
                }

答案 3 :(得分:1)

如果您使用的是Kotlin,则可以使用Google I/O Android app

中使用的扩展功能
fun RecyclerView.clearDecorations() {
   if (itemDecorationCount > 0) {
     for (i in itemDecorationCount - 1 downTo 0) {
         removeItemDecorationAt(i)
     }
   }
}

答案 4 :(得分:0)

这在科特林中对我有用:

var itemDecoration: RecyclerView.ItemDecoration? = null

while (recycler_view.itemDecorationCount > 0 && (recycler_view.getItemDecorationAt(0)?.let { itemDecoration = it }) != null) {
    recycler_view.removeItemDecoration(itemDecoration)
}

答案 5 :(得分:0)

在这里添加到Szymon Chaber的答案是kotlin扩展,以使其可重用:

fun <T : RecyclerView> T.removeItemDecorations() {
    while (itemDecorationCount > 0) {
        removeItemDecorationAt(0)
    }
}

答案 6 :(得分:0)

这是我创建的Kotlin扩展功能,用于删除所有recyclerView的物品装饰。

    /**
     * removes all recyclerview item decorations
     *
     */
    fun RecyclerView.removeItemDecorations() {
        while (this.itemDecorationCount > 0) {
            this.removeItemDecorationAt(0)
        }
    }

我通过调用以下命令来使用它:

recyclerView.removeItemDecorations()

请不要忘记计划在其中使用扩展功能的任何类的顶部import <path to extensions file>._KotlinExtensions.removeItemDecorations