DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • The Complete Guide to Stream API and Collectors in Java 8
  • The Foundations for Building an Apache Flink Application
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Clean Up Event Data in Ansible Event-Driven Automation

Trending

  • Server-Driven UI: Agile Interfaces Without App Releases
  • Deploy Serverless Lambdas Confidently Using Canary
  • Cell-Based Architecture: Comprehensive Guide
  • Maximizing Return on Investment When Securing Our Supply Chains: Where to Focus Our Limited Time to Maximize Reward
  1. DZone
  2. Data Engineering
  3. Data
  4. Click Listener for RecyclerView Adapter

Click Listener for RecyclerView Adapter

In this tutorial, learn to create a click listener interface for RecyclerView for Android, with options like multiple listeners, and endless possibilities for the data.

By 
Pierce Zaifman user avatar
Pierce Zaifman
·
May. 03, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
45.4K Views

Join the DZone community and get the full member experience.

Join For Free

There is a common pattern I use in all of my Android RecyclerView adapters to listen for click events on each item. I created an interface that is similar to the normal click listener, except it also has the position as a parameter.

public interface RecyclerViewClickListener {

    void onClick(View view, int position);
}

With this interface, I can set up a view holder class as a click listener, and pass in an instance of my interface. Then I set the view itself as a click listener and call my interface with the appropriate position.

public class RowViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private RecyclerViewClickListener mListener;

    RowViewHolder(View v, RecyclerViewClickListener listener) {
        super(v);
        mListener = listener;
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        mListener.onClick(view, getAdapterPosition());
    }
}

In your case you may not want to set the entire view as a click listener, maybe you have a button inside your layout. You can set it on that instead if you want, or add multiple listeners if you have multiple buttons for example. This is just a simple example to demonstrate how it works.

Now that I have a view holder, I can use it in my adapter.

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

        private RecyclerViewClickListener mListener;
        private List<Data> mDataset = new ArrayList<>();

        RecyclerViewAdapter(RecyclerViewClickListener listener) {
            mListener = listener;
        }

        public void updateData(List<Data> dataset) {
            mDataset.clear();
            mDataset.addAll(dataset);
            notifyDataSetChanged();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            View v = LayoutInflater.from(context).inflate(R.layout.my_layout, parent, false);
            return new RowViewHolder(v, mListener);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof RowViewHolder) {
                RowViewHolder rowHolder = (RowViewHolder) holder;
                //set values of data here
            }
        }

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

I pass in my interface to the adapter so it can pass it to the view holder. There is only one instance of this listener, all of the views call back to the same instance. Since they are differentiated by the position being passed in, there’s no need to have multiple instances. I create this listener when the adapter is instantiated.

Lastly, here is an example of a fragment where I create this listener.

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.my_fragment, container, false);

        RecyclerView recyclerView =  (RecyclerView) v.findViewById(R.id.my_recyclerview);

        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        RecyclerViewClickListener listener = (view, position) -> {
           Toast.makeText(getContext(), "Position " + position, Toast.LENGTH_SHORT).show();
        };
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(listener);
        recyclerView.setAdapter(adapter);

        return v;
    }

I am simply toasting the position that was tapped on, but you could do anything with the data at this point. For example, you may have a list of notes, and tapping on one gives you its position in the list. With that, you can get the data object from the list and display the details of that note to the user.

Interface (computing) Pass (software) Data (computing) Fragment (logic) Android (robot) Event Object (computer science)

Published at DZone with permission of Pierce Zaifman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Complete Guide to Stream API and Collectors in Java 8
  • The Foundations for Building an Apache Flink Application
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Clean Up Event Data in Ansible Event-Driven Automation

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: