Home > Mobile >  how to add onClickListener in recylclerView
how to add onClickListener in recylclerView

Time:09-16

I don't know how to add onclicklistener to here, I've tried many ways but it doesn't work, i made this with recyclerview, I've tried to add a new variable in the adapter section but error, I've also made activity details so I just need to hit recyclerview and go to details page, I gave the code that has not been added onclicklistener

please asap thank you;D

this MainActivity

class MainActivity : AppCompatActivity() {


private lateinit var adapter: MakeUpAdapter


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

  
    rv_kamu.setHasFixedSize(true)
    rv_kamu.layoutManager = LinearLayoutManager(this)
    adapter = MakeUpAdapter()
    adapter.notifyDataSetChanged()
    rv_kamu.adapter = adapter
    getDataFromApi()

  

}


private fun getDataFromApi() {
    Retrofit.instance.getMakeUpList()
        .enqueue(object : Callback<ArrayList<MakeUpModel>>{
            override fun onResponse(
                call: Call<ArrayList<MakeUpModel>>,
                response: Response<ArrayList<MakeUpModel>>
            ) {
                if(response.isSuccessful) {
                    showData(response.body()!!)
                }
            }

            override fun onFailure(call: Call<ArrayList<MakeUpModel>>, t: Throwable) {
                Log.e("Fail", "Be Fail")
            }

        })
}

private fun showData(data: ArrayList<MakeUpModel>) {
    val result = data
    adapter.setData(result)
}


}

and this adapter

class MakeUpAdapter : RecyclerView.Adapter<MakeUpAdapter.MakeUpViewHolder>(){



private val data = ArrayList<MakeUpModel>()

inner class MakeUpViewHolder (itemView: View) : RecyclerView.ViewHolder(itemView){


    fun bind(data: MakeUpModel) {
        //lib3
        Glide.with(itemView.context)
            .load(data.Picture)
            .apply(
                RequestOptions()
                    .override(100, 100)
            )
            .into(itemView.iv_item)

        itemView.tv_Name.text = data.Name


    }

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MakeUpViewHolder {
    val view: View =
        LayoutInflater.from(parent.context).inflate(R.layout.item_makeup, parent, false)
    return MakeUpViewHolder(view)
}


override fun onBindViewHolder(holder: MakeUpViewHolder, position: Int) {
    holder.bind(data[position])
}

override fun getItemCount(): Int = data.size


@SuppressLint("NotifyDataSetChanged")
//buat mainac
fun setData(list: ArrayList<MakeUpModel>) {
    data.clear()
    data.addAll(list)
    notifyDataSetChanged()
}



}

CodePudding user response:

This is my way.

first, create a interface to listen click event:

interface RecycleViewOnClickListener {
    fun onItemClick(pos :Int)
}

and in your adapter class, put interface in param, then call listener in onBindViewHolder:

class MakeUpAdapter(private val clickListener: RecycleViewOnClickListener) : RecyclerView.Adapter<MakeUpAdapter.MakeUpViewHolder>(){
    override fun onBindViewHolder(holder: MakeUpViewHolder, position: Int) {
        holder.bind(data[position])
        holder.itemView.setOnClickListener {
            clickListener.onItemClick(position)
        }
    }
}
}

In your activity, implement listener like this:

class MainActivity : AppCompatActivity(), RecycleViewOnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        adapter = MakeUpAdapter(this)
    }

    override fun onItemClick(pos: Int) {
        //do anything with your position here, such as get item from result
    }
}

Hope it's helpful for you

CodePudding user response:

on onBindViewHolder() you pass the position when calling the callback method:

override fun onBindViewHolder(holder: Holder?, position: Int) {
    var item : MyObject = objects[position]

    // Calling the clickListener sent by the constructor
    
holder.vieww.setOnClickListener {
     // click event
    }
}

CodePudding user response:

There are a few ways one could add a click listener, one way writing this more idiomatically might be:

class MainActivity : AppCompatActivity() {


    private val adapter by lazy { MakeUpAdapter() }

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

        rv_kamu.layoutManager = LinearLayoutManager(this)
        adapter.notifyDataSetChanged()
        adapter.listener = { /* TODO handle click event */ }
        rv_kamu.adapter = adapter
        getDataFromApi()

    }
}

class MakeUpAdapter : RecyclerView.Adapter<MakeUpAdapter.MakeUpViewHolder>(){
    var listener: (MakeUpModel) -> Unit = {}


    private val data = ArrayList<MakeUpModel>()

    inner class MakeUpViewHolder (itemView: View) : RecyclerView.ViewHolder(itemView){


         fun bind(data: MakeUpModel) {
              itemView.setOnClickListener { listener(data) }
              //bind data
         }

    }

    // plug in rest of your code


}

You might also want to consider moving the api call with retrofit into an Android ViewModel so that the network call will survive configuration changes (device rotation). This is a very simple example, but gets the point across and encourage you to check out the official android documentation on the subject.

class MakeUpViewModel( : ViewModel() {

    init {
        viewModelScope.launch {
             val response = Retrofit.instance.getMakeUpList()
             // update state with response
        }
    }

}
  • Related