Answer the question
In order to leave comments, you need to log in
How to add a new element to a random position every 2 seconds using Coroutines in RecyclerView?
Everything works like this: ViewModel - gives the list via LiveData MainActivity - gives the list via the setElem() method Adapter - determines the pressed position to be deleted and gives information about the position through the callBack MainActivity - gives info ViewModel - removes the element from the list
Adapter for RecycleView
ItemAdapter(
var context: Context,var recyclerViewClickInterface: RecyclerViewClickInterface
)
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
var positionOfNumber:NumberModel = myArrayElement!!.get(position)
holder.textOfNumber.text = positionOfNumber.numberOfElement
holder.button.setOnClickListener {
var positionForDelete = holder.adapterPosition
recyclerViewClickInterface.onClick(positionForDelete)
}
}
class MainActivityViewModel : ViewModel() {
var localElements = MutableLiveData<MutableList<NumberModel>>()
init {
localElements.value = setElements()
}
fun onElementClicked(index: Int) {
val copyOfArrayList:MutableList<NumberModel> = localElements.value!!
copyOfArrayList.removeAt(index)
localElements.value = copyOfArrayList
}
fun setElements() : MutableList<NumberModel> {
val itemArrayList:MutableList<NumberModel> = ArrayList()
itemArrayList.add(NumberModel("1"))
itemArrayList.add(NumberModel("2"))
itemArrayList.add(NumberModel("3"))
itemArrayList.add(NumberModel("4"))
itemArrayList.add(NumberModel("5"))
return itemArrayList
}
}
class MainActivity () : AppCompatActivity(), RecyclerViewClickInterface {
private var recyclerView:RecyclerView? = null
private var model: MainActivityViewModel? = null
private var gridLayoutManager:GridLayoutManager? = null
private var adapter:ItemAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
model= ViewModelProvider(this).get(MainActivityViewModel::class.java)
recyclerView = findViewById(R.id.recyclerViewList)
gridLayoutManager = GridLayoutManager(applicationContext,2,LinearLayoutManager.VERTICAL,false)
recyclerView?.layoutManager = gridLayoutManager
adapter = ItemAdapter(this,this)
recyclerView?.setHasFixedSize(true)
model!!.localElements.observe(this,{
adapter!!.setElem(it)
})
adapter?.notifyDataSetChanged()
recyclerView?.adapter = adapter
}
override fun onClick(position: Int) {
model!!.onElementClicked(position)
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question