Cha*_*ltz 9 android android-layout android-recyclerview
我正在使用水平RecyclerView,PagerSnapHelper使它看起来像一个ViewPager.它正在显示CardViews.
我的问题是,我怎样才能让它显示下一张和上一张卡的边缘?用户需要看到一些这样的卡片,以便他们直观地理解他们需要水平滑动以便他们可以查看其他卡片.
我还要注意,当前的卡片总是需要居中,即使对于第一张卡片,也不需要在左侧偷看之前的卡片.此外,设计要求不受我的控制; 我需要偷看,我不能使用点指示器或其他任何东西.
我可以使用a LinearSnapHelper并使卡片的宽度变小,但是1)第一项将左对齐而不是居中,因为左侧没有卡片偷看,2)每张卡片显示的数量会有所不同在手机的宽度上.
这似乎应该是一个普通而简单的任务,所以我希望我遗漏了一些明显的事情来实现它.
经过一番尝试和错误,我找到了解决方案。幸运的是,它并不像我想象的那么复杂,尽管没有我希望的那么干净。
因此,从 RecyclerView 及其适配器开始,使用水平方向的 LinearLayoutManager,添加 PagerSnapHelper 等等......然后为了解决这个问题中的具体问题,我对适配器做了一些调整:
private var orientation: Int? = null
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
orientation = (recyclerView.layoutManager as LinearLayoutManager).orientation
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Kludge to adjust margins for horizontal, ViewPager style RecyclerView
if (orientation != LinearLayout.VERTICAL) {
holder.itemView.layoutParams = (holder.itemView.layoutParams as RecyclerView.LayoutParams).apply {
val displayMetrics = DisplayMetrics()
baseActivity.windowManager.defaultDisplay.getMetrics(displayMetrics)
// To show the edge of the next/previous card on the screen, we'll adjust the width of our MATCH_PARENT card to make
// it just slightly smaller than the screen. That way, no matter the size of the screen, the card will fill most of
// it and show a hint of the next cards.
val widthSubtraction = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40f, displayMetrics).toInt()
width = displayMetrics.widthPixels - widthSubtraction
// We always want the spot card centered. But the RecyclerView will left-align the first card and right-align the
// last card, since there's no card peeking on that size. We'll adjust the margins in those two places to pad it out
// so those cards appear centered.
// Theoretically we SHOULD be able to just use half of the amount we shrank the card by, but for some reason that's
// not quite right, so I'm adding a fudge factor developed via trial and error to make it look better.
val fudgeFactor = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, displayMetrics).toInt()
val endAdjustment = (widthSubtraction / 2) - fudgeFactor
marginStart = if (position == 0) endAdjustment else 0
marginEnd = if (position == (itemCount - 1)) endAdjustment else 0
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您需要将40f和更改6f为适合您的用例的值。
如果您想知道,我进行了方向检查,因为在我的情况下,相同的适配器用于两个不同的 RecyclerView。一种是简单的垂直列表。另一种是横向的,功能类似ViewPager,大大增加了复杂度。
| 归档时间: |
|
| 查看次数: |
506 次 |
| 最近记录: |