I have list of contacts in where i select multiple items and pass to another activity ,In Recyclerview after selecting multiple items how do i pass it to another activity here is my Adapter class
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val item = contact[position]
holder.name.text = item.name
holder.number.text = item.number
holder.linlay.setOnLongClickListener{
selectItem(holder,item,position)
true
}
holder.linlay.setOnClickListener{
if(itemSelected.contains(position)){
itemSelected.remove(position)
holder.linlay.setBackgroundColor(Color.DKGRAY)
item.isSelect = false
if(itemSelected.isEmpty()){
isEnable=false
}
}
else if(isEnable){
selectItem(holder,item,position)
}
}
}
private fun selectItem(holder: ContactAdapter.ContactViewHolder, item: ContactModel, position: Int) {
isEnable = true
itemSelected.add(position)
item.isSelect = true
holder.linlay.setBackgroundColor(Color.YELLOW)
}
Where button for going to another activity is instead of recyclerview is in mainActivity class
class Mainactivity : AppComapctActivity(){
ovveride fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn_send = findViewById<Button>(R.id.btn_send)
btn_send.setOnClickListner{
val intent = Intent(this,HomeActivity::class.java)
startActivity(intent)
}
}
CodePudding user response:
When you select a contact in your selectItem
method you should create a MutableList
of contacts like MutableList inside of this list you will store the selected contacts previously, since you can remove/update the selected contact list you should be using MutableList
after you select all your contacts you should have a button to go to the next screen. There you should only send the MutableList of ContactModel
Let me do some pseudocode for you
private fun selectItem(holder: ContactAdapter.ContactViewHolder, item: ContactModel, position: Int) {
isEnable = true
itemSelected.add(position)
item.isSelect = true
holder.linlay.setBackgroundColor(Color.YELLOW)
if(item.isSelect)
myMutableContactList.add(item)
else
myMutableContactList.remove(item)
}
remember to create first the mutableList like
val myMutableContactList = mutableListOf<ContactModel>()
and then if you have a button to go to the next screen just send this list
When you press the button and go to the next fragment/activity a good practice will be to convert this mutablelist
to a list
since it will not change after beign send.
You can do it by simple using toList()
on your mutableList