如何解决两列宽度相等的 Android Studio CardView
我试图在卡片视图中每行(两列)显示两个元素。但是,它们不在卡片视图中居中。 click here to see how the cardview displays items
这里是xml中的代码:
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#Ffdb78"
android:layout_below="@+id/LinearLayoutCateg"
android:layout_above="@+id/menu"
android:id="@+id/currentCategoryRecyclerView"/>
我在 Main 活动中以编程方式创建了一个新的 GridLayoutManager,如下所示:
recyclerView.setLayoutManager(new GridLayoutManager(CategoryListActivity.this,2));
recyclerView.setAdapter(categoryRecycler);
cardview 位于具有 "android:gravity="center"
属性的相对布局中,如果这很重要的话。
我不确定我错过了什么。
解决方法
我和你有同样的问题,我找到了 RecyclerView Spacing 的 RecyclerView.ItemDecoration
类。
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int mItemOffset;
public ItemOffsetDecoration(int itemOffset) {
mItemOffset = itemOffset;
}
public ItemOffsetDecoration(@NonNull Context context,@DimenRes int itemOffsetId) {
this(context.getResources().getDimensionPixelSize(itemOffsetId));
}
@Override
public void getItemOffsets(Rect outRect,View view,RecyclerView parent,RecyclerView.State state) {
super.getItemOffsets(outRect,view,parent,state);
outRect.set(mItemOffset,mItemOffset,mItemOffset);
}
}
将 ItemOffsetDecoration
添加到您的 RecyclerView。
项目 offset 值应该是您要在项目之间添加空格的实际值的一半。
mRecyclerView.setLayoutManager(new GridLayoutManager(context,NUM_COLUMNS);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context,R.dimen.item_offset);
mRecyclerView.addItemDecoration(itemDecoration);
此外,将 item offset 值设置为其 RecyclerView 的填充,并指定 android:clipToPadding=false
。
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:padding="@dimen/item_offset"/> <!--Give a desired size-->
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。