Home > front end >  how to add second click listener to the recyclerview kotlin android?
how to add second click listener to the recyclerview kotlin android?

Time:11-13

I am trying to integrate a second click listener on recyclerview but I could not do it.

I am developing a checklist and I created recyclerview. Inside the recyclerview, there are a checkbox and textview. I can handle the click listener on textview or on itemclick.

But I can not handle the checkbox, check or uncheck event?

I am storing the data on Firebase but this is not a problem. I just can not handle second click listener on adapter class.

Thank you very much for your answers in advance.

adapter class

package com.example.shoppinglist

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class CheckListRecyclerViewAdapterClass (
    var checkList: List<CheckListModelClass>,
    private val clickListener: (CheckListModelClass) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var checkListTotalList: List<CheckListModelClass> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        val myView = LayoutInflater.from(parent.context).inflate(R.layout.check_list_rec_view_model_layout, parent, false)

        return CheckListViewHolder(myView)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        (holder as CheckListViewHolder).bind(checkListTotalList[position], clickListener)

    }

    override fun getItemCount(): Int {
        return checkListTotalList.size
    }

    fun submitList(checkList: List<CheckListModelClass>) {
        checkListTotalList = checkList
    }

    fun updateList(checkList: List<CheckListModelClass>) {
        checkListTotalList = checkList
        notifyDataSetChanged()
    }

    class CheckListViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val checkListCheckBox: CheckBox = itemView.findViewById(R.id.check_list_rec_view_model_layout_checkBox)
        private val checkListTextView: TextView = itemView.findViewById(R.id.check_list_rec_view_model_layout_textView)

        fun bind(
            checkListModelClass: CheckListModelClass,
            clickListener: (CheckListModelClass) -> Unit
        ) {

            checkListTextView.text = checkListModelClass.checkListItemName

            val checkListCheckBoxPosition = checkListModelClass.checkListItemCheckListPosition
            checkListCheckBox.isChecked = checkListCheckBoxPosition

            checkListTextView.setOnClickListener { clickListener(checkListModelClass) }
        }
    }

}

main activity;

package com.example.shoppinglist

import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.Source


class MainActivity : AppCompatActivity() {

    private var checkListTotalListArray = ArrayList<CheckListModelClass>()
    private lateinit var checkListRecyclerViewAdapterClass: CheckListRecyclerViewAdapterClass
    private lateinit var checkListModelClass: CheckListModelClass
    private lateinit var addItemToListEditText: EditText
    private lateinit var firebaseFirestore: FirebaseFirestore

    private lateinit var collectionReference: CollectionReference
    private lateinit var source: Source

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        firebaseFirestore = FirebaseFirestore.getInstance()
        collectionReference = firebaseFirestore.collection("shoppingList")
        checkListTotalListArray = arrayListOf()

        checkListRecyclerViewAdapterClass =
            CheckListRecyclerViewAdapterClass(checkListTotalListArray) { checkListModelClassItem: CheckListModelClass ->
                checkListClickListener(checkListModelClassItem)
            }

        takeDataFromFireStore()

        //recyclerview
        val checkListRecyclerView = findViewById<RecyclerView>(R.id.check_list_recycler_view)
        val checkListTotalListLayoutManager = LinearLayoutManager(this)
        checkListTotalListLayoutManager.orientation = LinearLayoutManager.VERTICAL
        checkListRecyclerView.layoutManager = checkListTotalListLayoutManager
        checkListRecyclerView.adapter = checkListRecyclerViewAdapterClass

        addItemToListEditText = findViewById(R.id.check_list_fragment_item_enter_edit_text)
        addItemToListEditText.imeOptions = EditorInfo.IME_ACTION_DONE
        addItemToListEditText.isSingleLine = true
        addItemToList()

    }

    private fun checkListClickListener(checkListModelClass: CheckListModelClass) {
        //handle click listener
        Toast.makeText(this, "first click listener", Toast.LENGTH_LONG).show()
    }

    private fun checkListClickListenerTwo(checkListModelClass: CheckListModelClass) {
        //handle click listener
        Toast.makeText(this, "first click listener two", Toast.LENGTH_LONG).show()
    }

    private fun takeDataFromFireStore(){
        checkListTotalListArray.clear()
        collectionReference.get().addOnSuccessListener { documents ->
            if (!documents.isEmpty) {
                for (document in documents){
                    val resultForCheckListItems: CheckListModelClass = document.toObject<CheckListModelClass>(CheckListModelClass::class.java)
                    checkListTotalListArray.add(resultForCheckListItems)
                }

                checkListRecyclerViewAdapterClass.submitList(checkListTotalListArray)
                checkListRecyclerViewAdapterClass.notifyDataSetChanged()
            }
        }
            .addOnFailureListener { exception ->
                Log.w("listen_data", "Error getting documents: ", exception)
            }

    }

    private fun saveDataToFireStore(){
        collectionReference.document()
            .set(checkListModelClass, SetOptions.merge())
            .addOnSuccessListener {
                takeDataFromFireStore()
                Log.d("TAG", "DocumentSnapshot successfully written!")
            }
            .addOnFailureListener { e -> Log.w("TAG", "Error writing document", e) }
    }

    private fun addItemToList(){
        addItemToListEditText.onDone { addItemToListEditText.hideKeyboard() }

    }
    private fun View.hideKeyboard() {
        val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
    }

    private fun EditText.onDone(callback: () -> Unit) {
        // These lines optional if you don't want to set in Xml
        imeOptions = EditorInfo.IME_ACTION_DONE
        maxLines = 1
        setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {

                // Your action on done
                if(addItemToListEditText.text.toString() != "") {
                    checkListModelClass =
                        CheckListModelClass(false, addItemToListEditText.text.toString())
                    saveDataToFireStore()
                    //checkListTotalListArray.add(checkListModelClass)
                    //checkListRecyclerViewAdapterClass.updateList(checkListTotalListArray)
                    addItemToListEditText.text.clear()
                }

                callback.invoke()
                true
            }
            false
        }
    }
}

model class;

package com.example.shoppinglist

class CheckListModelClass(
   var checkListItemCheckListPosition: Boolean = false,
   var checkListItemName: String = ""
)

CodePudding user response:

Click listener won't mostly work for CheckBox. What you could do is wrap it in any ViewGroup like LinearLayout and use that ViewGroup to implement your click listener.

You can do it in XML or programmatically. If that is what you really want, wrap it in a ViewGroup.

CodePudding user response:

But I can not handle the checkbox, check or uncheck event?

If I understand this correctly, you want to listen to its check/uncheck event. Normally you can do it via listening to a click event or listening to its state change.

As mentioned by @cactustictacs , you can simply use setOnClickListener to determine if the view (checkbox) has been clicked and using the actual instance of checkbox for your intended conditional logic.

checkListCheckBox.setOnClickListener {
    if (checkListCheckBox.isChecked) {
         ...
    } else {
         ...
    }
}

But if you want to listen when its checked state changes, you can use setOnCheckedChangeListener, with this function you can simply use the view from the lambda parameter or the boolean state

checkListCheckBox.setOnCheckedChangeListener { view, isChecked ->  
     if (view.isChecked) { // or simply if (isChecked) {..}
         ...
     } else {
         ...
     }
}
  • Related