带有CardViews的RecyclerView的ItemDecorator无法正常工作

时间:2016-10-12 16:04:09

标签: android android-recyclerview spacing

我正在尝试使用ItemDecorator在RecyclerView中实现CardViews之间的间距。为此,我使用了作为参考this的答案,但没有应用间距。我也试过this回答,但没有用。

以下是RecyclerView的XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.company.name.MyFragment">

    <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerviewId"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            />
</FrameLayout>

以下是CardView的XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cardView"
        card_view:cardElevation="2dp"
        >

    <android.support.constraint.ConstraintLayout
            android:id="@+id/constraintLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <ImageView
                android:id="@+id/imageView"
                android:layout_width="100dp"
                android:layout_height="98dp"
                card_view:srcCompat="@mipmap/ic_launcher"
                card_view:layout_constraintTop_toTopOf="parent"
                card_view:layout_constraintLeft_toLeftOf="parent"/>
    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>

项目装饰器的代码是参考咨询中提供的代码。

不能应用间距的原因是什么?

编辑1:

这里是分配项装饰器的代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    ...

    myRecyclerView.setLayoutManager(new GridLayoutManager(activity, 2));
    myRecyclerView.addItemDecoration(new SpacingGridView(activity, R.dimen.my_spacing), 0);

    ... 
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState)

    MyAdapter adapter = MyAdapter(getData());
    myRecyclerView.setAdapter(adapter);
}

0 个答案:

没有答案