skip to Main Content

Basically, I am creating a messaging app. So, I created a RecyclerView in which an ArrayList of Objects(Mobile Numbers) are stored. On clicking on any of the objects, opens the layout that shows all the messages sent by the clicked Mobile number. That’s why I am trying to figure out how to access the object that has been clicked.

Haven’t tried anything yet. Still trying to figure out what to do.

2

Answers


  1. Here is the code.

    @Override
    public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
    
        int selectedPosition = position;
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
    //  this is how you access the clicked Mobile number if you have stored it an array 
                String phoneNum = yourArray.get(selectedPosition).toString();
    
                Intent intent = new Intent(context, YourNewActivity.class);
    // to pass the phone number to the next activity where you can get it with getIntent()
    intent.putExtra( PHONE_NUM , phoneNum);
                context.startActivity(intent);
            }
        });
    }
    

    Let me know if you have any problems in understanding the code.

    Login or Signup to reply.
  2. Do it in a efficient way.
    First create a interface and declare it in your adapter class..

    public interface ClickListener {
        void itemClick(int position);
    }
    
    private ClickListener clickListener;
    

    Than on onBindViewHolder call it.

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickListener.itemClick(position);
            }
        });
    }
    

    Now from your activity where you called the adapter implement the interface, after implement you can easily override this onClick method there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search