我正在创建一个具有三列的垂直RecyclerView(为简化说明,我使RecyclerView仅包含6个项目)。我需要的是两侧的物品都具有更大的边距,因此我使用ItemDecoration来实现这一点:
class SpaceDecoration : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
outRect.left = when(position) {
0, 3 -> 160 // Left most two items
else -> 10 // others
}
outRect.right = when(position) {
2, 5 -> 160 // Right most two items
else ->0 // others
}
outRect.top = 10
outRect.bottom = 0
}
}
我想要的是项目主体具有相同的宽度。但是,事实并非如此。看起来GridLayoutManager在平均划分空间时会测量ItemDecoration的大小。如何使项目看起来相等的宽度?我当然不希望GridLayoutManager测量ItemDecoration。
这是剩余的代码:
MainActivity.kt:
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.grid)
recyclerView.layoutManager = GridLayoutManager(this,3, RecyclerView.VERTICAL, false)
recyclerView.adapter = GridAdapter()
recyclerView.addItemDecoration(SpaceDecoration())
}
}
GridAdapter.kt:
class GridAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
VH(LayoutInflater.from(parent.context).inflate(R.layout.grid_item, parent, false))
override fun getItemCount() = 6
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = Unit
class VH(item: View) : RecyclerView.ViewHolder(item)
}
grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="AAA"
android:gravity="center"
android:background="@color/colorAccent"/>
答案 0 :(得分:0)
您可以将paddingLeft
和paddingRight
添加到recyclerView
中(不添加任何ItemDecoration
)。会有填充,元素的大小将相等。