我有一个recyclerView,其中包含我想在特定事件发生时滚动到的项目列表。我正在使用 v
red green blue purple # print red
# next
v
red green blue purple # print green
v
red blue purple # delete green in the same iteration
# next
v
red blue purple # print purple
但令我惊讶的是,它不仅没有光滑,而且我得到一个闪烁效果,就像它必须在实际滚动之前恢复基本位置。效果可以在这里看到:
http://i.imgur.com/rrpLr7N.mp4
这是正常行为吗?
适配器代码:
smoothScrollToPosition
布局文件:
@ActivityScope
class HighlightListAdapter @Inject constructor() : RecyclerView.Adapter<HighlightListAdapter.ViewHolder>() {
private var highlights: List<Highlight> = emptyList()
private var itemClick: ((Highlight, Int) -> Unit)? = null
private var selectedRow: MutableList<Int> = mutableListOf()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val binding = holder.binding
val highlight = highlights[position]
var viewModel = binding.viewModel
viewModel?.unbind()
viewModel = HighlightViewModel(highlight)
binding.viewModel = viewModel
viewModel.bind()
if(selectedRow.contains(position)) {
binding.rootItemView.alpha = 1.0f
}
else {
binding.rootItemView.alpha = 0.5f
}
holder.setClickListener(itemClick)
}
override fun getItemCount(): Int = highlights.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = DataBindingUtil.inflate<ItemHighlightListBinding>(
LayoutInflater.from(parent.context),
R.layout.item_highlight_list,
parent,
false
)
return ViewHolder(binding)
}
fun updateEvents(highlights: List<Highlight>) {
this.highlights = highlights
notifyDataSetChanged()
}
fun setClickListener(itemClick: ((Highlight, Int) -> Unit)?) {
this.itemClick = itemClick
}
fun enableRow(index: Int) {
//Clear previous selection (only if we want single selection)
selectedRow.clear()
//Select specified row
selectedRow.add(index)
//Let the adapter redraw
notifyDataSetChanged()
}
class ViewHolder(val binding: ItemHighlightListBinding) : RecyclerView.ViewHolder(binding.root) {
fun setClickListener(callback: ((Highlight, Int) -> Unit)?) {
binding.viewModel.clicks().subscribe {
callback?.invoke(binding.viewModel.highlight, adapterPosition)
}
}
}
fun getSelected() = selectedRow
}
答案 0 :(得分:2)
我认为问题在于启用行notifyDataSetChanged()。它刷新整个数据集,导致轻弹列表。试试这个
fun enableRow(index: Int) {
//Clear previous selection (only if we want single selection)
selectedRow.clear()
//Select specified row
selectedRow.add(index)
//Let the adapter redraw
notifyItemRangeChanged(index,highlights.size())
}