0
我試圖構建這種佈局 - 只有兩列網格圖像和圖像下面的圖像。RecyclerView的ItemDecoration打破使用ConstraintLayout構建的項目佈局
我想建立這種使用RecyclerView,GridLayoutManager和ItemDecoration爲項目之間的間隔。這就是我得到的結果,因爲您可以看到右側圖像下方的文字已移到底部。
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SpacesItemDecoration());
Adapter adapter = new Adapter();
recyclerView.setAdapter(adapter);
}
}
SpacesItemDecoration
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.bottom = 20;
if (parent.getChildLayoutPosition(view) % 2 == 0) {
outRect.right = 20;
} else {
outRect.right = 0;
}
}
}
item.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#DDDDDD"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="h,4:5"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@+id/text_view"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="@+id/text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:textStyle="bold"
android:gravity="center"
app:layout_constraintTop_toBottomOf="@+id/image_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>
您可以從GitHub