首页 > 解决方案 > Recycler ItemDecoration - 未绘制分隔线,不确定原因

问题描述

我试图在我的垂直回收视图中显示一些分隔线。当我使用提供的默认分隔符时:

 mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
 mRecycler.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
  mRecycler.setAdapter(adapter);

它工作得很好。但是,当我编写自己的自定义类时,什么都没有显示,我也不知道为什么。

public class PostDivider extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public PostDivider(Context context) {
        mDivider = ContextCompat.getDrawable(context, R.drawable.divider_horizontal);
    }

    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

}

这是R.drawable.divider_horizontal

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:height="16dp" />
    <solid android:color="@color/steelBlue" />
</shape>

添加我的自定义分隔线:

mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
mRecycler.addItemDecoration(new PostDivider(mContext));
mRecycler.setAdapter(adapter);

编辑:我换成了mContextgetActivity() 并且它没有返回 null。所以我很迷茫为什么它不起作用

Edit2:似乎是一个观众问题

我将整个视图简化为:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorWhite"
    android:layout_margin="20dp">

    <ImageView
        android:id="@+id/vh_buisnesspost_buisness_preview"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/background_circle_preview_border"/>

    <ImageView
        android:id="@+id/vh_buisnesspost_post_image"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/colorAccent"
        android:layout_below="@id/vh_buisnesspost_buisness_preview"/>


</RelativeLayout>

这是我感到困惑的地方:为什么当您添加到父布局时它只显示分隔线?!!!!android:layout_margin="20dp"

android:layout_marginBottom="20dp"不工作只是android:layout_margin="20dp"为什么?!!!!!!

标签: android

解决方案


推荐阅读