Home > Net >  How do I set onClick listner to recyclerView in Android [Java]
How do I set onClick listner to recyclerView in Android [Java]

Time:09-27

I want to add onClick to recyclerView so that i can send data back to form Activity for update data process.How can I implement onItemClickListner when this code don't have adapter in it?. Please give explanation with your answer.

Here is my code :

Show_Employees.java

 package com.example.roomdatabaseandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.roomdatabaseandroid.DataModel.EmployeeDao;
import com.example.roomdatabaseandroid.DataModel.EmployeeDatabase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class ShowEmployees extends AppCompatActivity {

    private static final int EDIT_COURSE_REQUEST = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_employees);

        RecyclerView recyclerView;
        FloatingActionButton fab = findViewById(R.id.idFABAdd);
        EmployeeDao employeeDao;

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //starting a new activity for adding a new course and passing a constant value in it.
                Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
                startActivity(intent);
            }
        });

        employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
        recyclerView = findViewById(R.id.employeeRecyclerView);

        EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(employeeRecycler);




        //below method is use to add swipe to delete method for item of recycler view.
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                //on recycler view item swiped then we are deleting the item of our recycler view.
                employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
                Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
            }
        }).attachToRecyclerView(recyclerView);
    }
}

Employee_Recycler.java

    package com.example.roomdatabaseandroid;
    
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.example.roomdatabaseandroid.DataModel.DataConverter;
    import com.example.roomdatabaseandroid.DataModel.Employee;
    
    import java.util.List;
    
    public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
    
        List<Employee> data;
    
        public EmployeeRecycler(List<Employee> employees){
            data = employees;
        }
    
        @NonNull
        @Override
        public EmployeeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.list_item_1,
                    parent,false
            );
            return new EmployeeViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(@NonNull EmployeeViewHolder holder, int position) {
            Employee employee = data.get(position);
            holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
            holder.firstName.setText(employee.getFirstName());
            holder.middleName.setText(employee.getMiddleName());
            holder.lastName.setText(employee.getLastName());
            holder.dob.setText(employee.getDOB());
            holder.gender.setText(employee.getGender());
            holder.address.setText(employee.getAddress());
            holder.designation.setText(employee.getDesignation());
            holder.email.setText(employee.getEmail());
            holder.phoneNumber.setText(employee.getPhoneNumber());
        }
    
        @Override
        public int getItemCount() {
            return data.size();
        }
    
    }

EmployeeViewHolder.java

package com.example.roomdatabaseandroid;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class EmployeeViewHolder extends RecyclerView.ViewHolder {

    ImageView imageView;
    TextView firstName,middleName,lastName,email,phoneNumber,address,designation,gender,dob;


    public EmployeeViewHolder(@NonNull View itemView) {
        super(itemView);
        firstName = itemView.findViewById(R.id.idTVFirstName);
        middleName = itemView.findViewById(R.id.idTVMiddleName);
        lastName = itemView.findViewById(R.id.idTVLastName);
        dob = itemView.findViewById(R.id.idTVDOB);
        address = itemView.findViewById(R.id.idTVAddress);
        gender = itemView.findViewById(R.id.idTVGender);
        designation = itemView.findViewById(R.id.idTVDesignation);
        email = itemView.findViewById(R.id.idTVEmail);
        phoneNumber = itemView.findViewById(R.id.idTVPhoneNumber);
        imageView = itemView.findViewById(R.id.profileImageView);
    }
}

Thank you in advance.

CodePudding user response:

add an interface

interface AdapterItemClickListener {
  void onItemClickListener(Employee employee, int position)
}

your actvity must implement this interface

public class ShowEmployees extends AppCompatActivity implements AdapterItemClickListener  {
        private static final int EDIT_COURSE_REQUEST = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_employees);

        RecyclerView recyclerView;
        FloatingActionButton fab = findViewById(R.id.idFABAdd);
        EmployeeDao employeeDao;

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //starting a new activity for adding a new course and passing a constant value in it.
                Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
                startActivity(intent);
            }
        });

        employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
        recyclerView = findViewById(R.id.employeeRecyclerView);

        EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee(), this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(employeeRecycler);




        //below method is use to add swipe to delete method for item of recycler view.
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                //on recycler view item swiped then we are deleting the item of our recycler view.
                employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
                Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
            }
        }).attachToRecyclerView(recyclerView);
    }

   void onItemClickListener(Employee employee, int position) {
      //update or another job
   }
}

and your adapter

   public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
        
            List<Employee> data;
            AdapterItemClickListener itemClickListener;
        
            public EmployeeRecycler(List<Employee> employees, AdapterItemClickListener itemClickListener){
                data = employees;
                this.itemClickListener = itemClickListener;
            }
        
            @NonNull
            @Override
            public EmployeeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.list_item_1,
                        parent,false
                );
                return new EmployeeViewHolder(view);
            }
        
            @Override
            public void onBindViewHolder(@NonNull EmployeeViewHolder holder, int position) {
                Employee employee = data.get(position);
                holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
                holder.firstName.setText(employee.getFirstName());
                holder.middleName.setText(employee.getMiddleName());
                holder.lastName.setText(employee.getLastName());
                holder.dob.setText(employee.getDOB());
                holder.gender.setText(employee.getGender());
                holder.address.setText(employee.getAddress());
                holder.designation.setText(employee.getDesignation());
                holder.email.setText(employee.getEmail());
                holder.phoneNumber.setText(employee.getPhoneNumber());
               
                holder.itemView.setOnClickListener (v -> { 
                   itemClickListener.onItemClickListener(employee, position);
               });
            }
        
            @Override
            public int getItemCount() {
                return data.size();
            }
        
        }
  • Related