Я реализую RecyclerView
и хочу получить подробную информацию о выбранных элементах.
Я следую учебнику, данному здесь . Но я хочу получить строковый ключ вместо позиции элемента.
Например, если мне так:
for (selection in selectionTracker?.selection!!)
Log.e("tag", selection.toString())
Я получаю индексы в качестве выходных данных, но я хочу получить строковые ключи здесь.
Но я не знаю, какие дальнейшие изменения должны быть сделаны, если я сделаю так:
fun getItemDetails() = object: ItemDetailsLookup.ItemDetails<Long>() {
override fun getSelectionKey() = itemId
override fun getPosition() = adapterPosition
}
и измените его на:
fun getItemDetails() = object: ItemDetailsLookup.ItemDetails<Long>() {
override fun getSelectionKey() = myData[adapterPosition].myKey // a string
override fun getPosition() = adapterPosition
}
---- EDIT ----
Вот мои коды:
Класс адаптера:
class AdapterSubjectsIndexRV (
private val indexList: ArrayList<ModelSubjectsIndex>,
val itemClick: (String) -> Unit
): RecyclerView.Adapter<AdapterSubjectsIndexRV.MyViewHolder>() {
// every recycler view item has unique id
init {
setHasStableIds(true)
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder.
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val courseValue = itemView.findViewById<TextView>(R.id.course_value)!!
val courseCode = itemView.findViewById<TextView>(R.id.course_code)!!
val courseName = itemView.findViewById<TextView>(R.id.course_name)!!
val progressValue = itemView.findViewById<TextView>(R.id.progress_value)!!
val progressBar = itemView.findViewById<ProgressBar>(R.id.progress_bar)!!
val selectedOverlay = itemView.findViewById<View>(R.id.subjects_card_view_selected)!!
// set click events
init {
itemView.setOnClickListener {
itemClick(courseCode.text.toString())
}
}
// get item details
fun getItemDetails() = object: ItemDetailsLookup.ItemDetails<String>() {
// override fun getSelectionKey() = itemId
override fun getSelectionKey() = indexList[adapterPosition].courseCode
override fun getPosition() = adapterPosition
}
}
// lookup class
class MyItemDetailsLookup(private val rv: RecyclerView): ItemDetailsLookup<String>() {
override fun getItemDetails(e: MotionEvent): ItemDetails<String>? {
val v = rv.findChildViewUnder(e.x, e.y)
return if (v != null) {
(rv.getChildViewHolder(v) as MyViewHolder).getItemDetails()
} else null
}
}
// set tracker
var tracker: SelectionTracker<Long>? = null
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterSubjectsIndexRV.MyViewHolder {
// create a new view
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.subjects_card, parent, false)
return MyViewHolder(itemView)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.courseValue.text = indexList[position].courseValue
holder.courseCode.text = indexList[position].courseCode
holder.courseName.text = indexList[position].courseName
holder.progressValue.text = "${indexList[position].progress}%"
holder.progressBar.progress = indexList[position].progress
// Highlight the item if it's selected
holder.selectedOverlay.visibility = if (tracker!!.isSelected(position.toLong())) View.VISIBLE else View.INVISIBLE
}
// Return the size of your data set (invoked by the layout manager)
override fun getItemCount() = indexList.size
override fun getItemId(position: Int): Long {
return position.toLong()
}
}
И вот как я устанавливаю свой фрагмент:
val rvAdapter = AdapterSubjectsIndexRV(getSubjectsIndexList(subjectsList)) {
// if not in selection mode
if (selectionTracker?.selection?.size() == 0) {
listener.showSubjectDetails(it)
}
}
// set recycler view
val recyclerView = theView.findViewById<RecyclerView>(R.id.subjects_recycler_view)
recyclerView.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity)
adapter = rvAdapter
}
// set selection tracker
selectionTracker = SelectionTracker
.Builder<Long>(
"subjects_index_selection",
recyclerView,
StableIdKeyProvider(recyclerView),
AdapterSubjectsIndexRV.MyItemDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
SelectionPredicates.createSelectAnything()
).build()
rvAdapter.tracker = selectionTracker
if(savedInstanceState != null)
selectionTracker?.onRestoreInstanceState(savedInstanceState)
return theView