【发布时间】:2020-01-11 18:35:13
【问题描述】:
从下面的图片可以看出,我几乎已经达到了我想要的效果。但是,RecyclerView 项目的大小不同。特别是,第 2 列 RecyclerView 与第 1 列的大小不同。
请注意,我已尝试实施来自 How to make RecyclerView's grid item to have equal height and width? 的解决方案,但我无法解决我的问题。
RecyclerView 项目:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<com.jackandphantom.circularimageview.RoundedImage
android:id="@+id/launcher_icon"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
XML 片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="@dimen/medium_margin"
android:layout_marginRight="@dimen/medium_margin" />
</LinearLayout>
片段.java:
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.medium_margin));
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity());
recyclerView.setAdapter(adapter);
return view;
}
ItemOffsetDecoration.java
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int mItemOffset;
private ItemOffsetDecoration(int itemOffset) {
mItemOffset = itemOffset;
}
public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {
this(context.getResources().getDimensionPixelSize(itemOffsetId));
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int position = parent.getChildLayoutPosition(view);
GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager();
if (manager != null && position < manager.getSpanCount()) outRect.top = mItemOffset;
if (position % 2 != 0) {
outRect.right = mItemOffset;
}
outRect.left = mItemOffset;
outRect.bottom = mItemOffset;
}
}
【问题讨论】:
标签: android