Recycler View Part - IV [Event]

Event Listener for Recycler View

Event Driven Programming

The essence of having a list of data is to be able to click or do some kind of actions with it. So after making a recycler view which is working with the data we have provided we should be able to do some actions with it.

Usually a recycler view is selected and we change activity into a new page which will show details.

So we should be able to know WHEN and WHICH recycler item is clicked. We should be able to know this click event to perform some actions after it.

This mechanism is termed as a callback. Using interfaces we can achieve this very easily.

Steps

1. Create an Interface

Create an Interface (same as creating a new Java class) and name it OnRecyclerItemClick. Interface will have interface keyword before the given name.

Create a void function name onClick which will take your CountryModel as a parameter.

public interface OnRecyclerItemClick {

    void onClick(CountryModel selectedCountry);

}

2. Logic in Adapter

So simply our logic is

  • We select a Country Item in Recycler
  • That country is assigned to Interface
  • The Interface will now holds the selectedCountry
  • The Interface holding the data is passed to MainActivity
  • MainActivity will receive the selectedCountry item in the Constructor.

Create a listener object in your SimpleRecyclerViewAdapter below your ArrayList declaration


 ArrayList<CountryModel> recyclerData = new ArrayList<CountryModel>();
//here
OnRecyclerItemClick listener;

Change your constructor which will accept a listener from where it is being called

 SimpleRecyclerViewAdapter(
            ArrayList<CountryModel> receivedData, OnRecyclerItemClick listener) {
        recyclerData = receivedData;
//new code
        this.listener = listener;
    }

Change your recycler view onBindViewHolder as

 @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            holder.name.setText(recyclerData.get(position).getName());
            holder.code.setText(recyclerData.get(position).getCountry_code());
            holder.area.setText(Integer.toString(recyclerData.get(position).getArea()));

//New Code

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    listener.onClick(recyclerData.get(position));
                }
            });

        }

Here the listener.onClick(item) will accept the currently selected country.

3. Adapter initialization in MainActivity

Now we need to receive data in our MainActivity which is possible by passing a interface in the Constructor where we initialize our SimpleRecyclerAdapter

adapter = new SimpleRecyclerViewAdapter(countryData, new OnRecyclerItemClick() {
    @Override
     public void onClick(CountryModel selectedCountry) {
        Toast.makeText(MainActivity.this, selectedCountry.getName(), Toast.LENGTH_SHORT).show();
      }
 });

Perfect!

You should now see a Toast for which country you click!

image.png

Total Adapter


public class SimpleRecyclerViewAdapter
        extends
        RecyclerView.Adapter<SimpleRecyclerViewAdapter.ViewHolder> {

    ArrayList<CountryModel> recyclerData = new ArrayList<CountryModel>();
    OnRecyclerItemClick listener;

    SimpleRecyclerViewAdapter(
            ArrayList<CountryModel> receivedData, OnRecyclerItemClick listener) {
        recyclerData = receivedData;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(
                LayoutInflater.from(
                        parent.getContext())
                        .inflate(
                                R.layout.layout_simple_recycler_item,
                                parent,
                                false
                        )
        );
    }
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            holder.name.setText(recyclerData.get(position).getName());
            holder.code.setText(recyclerData.get(position).getCountry_code());
            holder.area.setText(Integer.toString(recyclerData.get(position).getArea()));

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    listener.onClick(recyclerData.get(position));
                }
            });

        }

    @Override
    public int getItemCount() {
        return recyclerData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView code;
        TextView area;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            code = itemView.findViewById(R.id.code);
            area = itemView.findViewById(R.id.area);
        }
    }
}

Total Interface

public interface OnRecyclerItemClick {
    void onClick(CountryModel selectedCountry);
}

Total MainActivity

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    LinearLayoutManager linearLayoutManager;
    SimpleRecyclerViewAdapter adapter;
    OnRecyclerItemClick listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        getActionBar().hide();

        ArrayList<CountryModel> countryData = new ArrayList<>();

        countryData.add(new CountryModel(
                "Nepal",
                "+977",
                "Kathmandu",
                true,
                1578181,
                "https://flagcdn.com/w320/np.png"
        ));

        countryData.add(new CountryModel(
                "China",
                "+86",
                "Beijing",
                true,
                9706961,
                "https://flagcdn.com/w320/cn.png"
        ));

        countryData.add(new CountryModel(
                "India",
                "+91",
                "Delhi",
                true,
                3287590,
                "https://flagcdn.com/w320/in.png"
        ));

        recyclerView = findViewById(R.id.recycler_view);
        linearLayoutManager = new LinearLayoutManager(this,RecyclerView.VERTICAL, false);

        adapter = new SimpleRecyclerViewAdapter(countryData, new OnRecyclerItemClick() {
            @Override
            public void onClick(CountryModel selectedCountry) {
                Toast.makeText(MainActivity.this, selectedCountry.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(linearLayoutManager);

    }


}

Assignment

Please upload this working project as assignment of recycler-view-part-IV