How to add functionality to buttons of each of the recyclerview items?

北慕城南 提交于 2019-12-02 16:09:26

问题


I am writing an android code, wherein on clicking a button on the recyclerview, it should direct it to some other activity. The program should redirect the control to different activities for each of the recyclerview items. I have successfully added buttons to the template of the activity, however, I am not able to understand how to add functionality to each of the buttons. I am enclosing herewith the the different files that I have included in the project. It would be very helpful if someone could guide me how to proceed from here.

ProductPage1.java

package com.agnik.example.myapplication4;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import java.util.ArrayList;

public class ProductPage1 extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_page1);

        ArrayList<ExampleItem> exampleList = new ArrayList<>();
        exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
        exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
        exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
        exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
        exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
        exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
        exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
        exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
        exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
        exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
        exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
        exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));

        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new ExampleAdapter(exampleList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

    }
}

ExampleAdapter.java

package com.agnik.example.myapplication4;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

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

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {

    private ArrayList<ExampleItem> mExampleList;


    public static class ExampleViewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextView1;
        public TextView mTextView2;
        public Button mButton;

        public ExampleViewHolder(@NonNull View itemView) {
            super(itemView);
            mImageView = itemView.findViewById(R.id.imageView);
            mTextView1 = itemView.findViewById(R.id.textView);
            mTextView2 = itemView.findViewById(R.id.textView2);
            mButton = itemView.findViewById(R.id.mybutton);


        }
    }

    public ExampleAdapter(ArrayList<ExampleItem> exampleList)
    {

        mExampleList = exampleList;

    }

    @NonNull
    @Override
    public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
        ExampleViewHolder evh = new ExampleViewHolder(v);
        return evh;

    }

    @Override
    public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {

        ExampleItem currentItem = mExampleList.get(position);
        holder.mImageView.setImageResource(currentItem.getImageResource());
        holder.mTextView1.setText(currentItem.getText1());
        holder.mTextView2.setText(currentItem.getText2());

    }

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

    }







}

ExampleItem.java

    package com.agnik.example.myapplication4;

    public class ExampleItem {

        private int mImageResource;
        private String mText1;
        private String mText2;

        public ExampleItem(int imageResource, String text1, String text2) {
            mImageResource = imageResource;
            mText1 = text1;
            mText2 = text2;
        }

        public int getImageResource() {
            return mImageResource;
        }

        public String getText1() {
            return mText1;
        }

        public String getText2() {
            return mText2;
        }

    }

activity_product_page1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProductPage1">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#008080"
        android:padding="4dp"
        android:scrollbars="vertical" />

</RelativeLayout>

example_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="4dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:padding="2dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/imageView"
            android:text="Line 1"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            android:textStyle="bold"
            android:layout_toRightOf="@+id/imageView" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView"
            android:layout_marginStart="8dp"
            android:layout_toEndOf="@+id/imageView"
            android:text="Line 2"
            android:textSize="15sp"
            android:layout_marginLeft="8dp"
            android:layout_toRightOf="@+id/imageView" />

        <Button
            android:id="@+id/mybutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView2"
            android:layout_marginStart="8dp"
            android:layout_toEndOf="@+id/imageView"
            android:text="Purchase"
            android:textSize="15sp"
            android:layout_marginLeft="8dp"
            android:layout_toRightOf="@+id/imageView"  />


    </RelativeLayout>

</androidx.cardview.widget.CardView>

activity_product_page1.java

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProductPage1">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#008080"
        android:padding="4dp"
        android:scrollbars="vertical" />

</RelativeLayout>

enter image description here

EDIT:

As mentioned by Phil, I need to add setOnClickListener with the holder object. However, I am not able to understand how should I transfer control from ProductPage1.class to SomeOtherActivity.class as I am writing the code on ExampleAdapter.java?

   holder.mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (position) {
                    case 1:                 

                        Intent i = new Intent(ProductPage1.class, PageDemo1_1.class);
                        startActivity(i);
                        break;
                    case 2:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_2.class);
                        startActivity(i);
                        break;
                    case 3:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_3.class);
                        startActivity(i);
                        break;
                    case 4:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_4.class);
                        startActivity(i);
                        break;
                    case 5:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_5.class);
                        startActivity(i);
                        break;
                    case 6:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_6.class);
                        startActivity(i);
                        break;
                    case 7:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_7.class);
                        startActivity(i);
                        break;
                    default:
                        Intent i = new Intent(ProductPage1.class, PageDemo1_3.class);
                        startActivity(i);
                        break;
                }



            }
        });

回答1:


You have to do this inside the onBindViewHolder method in ExampleAdapter.

As an example you could do it like this:

@Override
public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {

    ExampleItem currentItem = mExampleList.get(position);
    holder.mImageView.setImageResource(currentItem.getImageResource());
    holder.mTextView1.setText(currentItem.getText1());
    holder.mTextView2.setText(currentItem.getText2());
    holder.mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // your code here
            }
    });

}

Inside the onBindViewHolder() method "the logic happens". There you can set up everything for each of the RecyclerView items.




回答2:


You need to create 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);
}

then you can declare in your adaper

private final RecyclerViewClickListener listener;

and you can create a setter in adapter

public void setListner(RecyclerViewClickListener listener){
this.listener=listener;
}



回答3:


You will have to add a callback Interface into the Adapter and pass an instance of the Interface from the Activity to the Adapter constructor. Call the method(s) of the interface when you click the different ViewGroup of the recyclerview items and there should be an implementation into the Activity. Your codes will look like this

Activity

    public class ProductPage1 extends AppCompatActivity implements ClickCallback {

        private RecyclerView mRecyclerView;
        private RecyclerView.Adapter mAdapter;
        private RecyclerView.LayoutManager mLayoutManager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_product_page1);

            ArrayList<ExampleItem> exampleList = new ArrayList<>();
            exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
            exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
            exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
            exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
            exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
            exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
            exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
            exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
            exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));
            exampleList.add(new ExampleItem(R.drawable.mickeymouse, "Line1" , "Line2"));
            exampleList.add(new ExampleItem(R.drawable.donalduck, "Line3" , "Line4"));
            exampleList.add(new ExampleItem(R.drawable.popey, "Line5" , "Line6"));

            mRecyclerView = findViewById(R.id.recyclerView);
            mRecyclerView.setHasFixedSize(true);
            mLayoutManager = new LinearLayoutManager(this);
            mAdapter = new ExampleAdapter(exampleList);

            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setAdapter(mAdapter);

        }

       @Override
       onItemClick(int position, View view){
        switch(view.getId()){
           case R.id.mImageView:
         //do your view click events here
            break;
           case R.id.mImageView2:
         //do your view click events here
           break;
         //so on
       }
 }

Adapter

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {

    private ArrayList<ExampleItem> mExampleList;


    public static class ExampleViewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextView1;
        public TextView mTextView2;
        public Button mButton;

        public ExampleViewHolder(@NonNull View itemView,ClickCallback clickCallback) {
            super(itemView);
this.clickCallback=clickCallback;
            mImageView = itemView.findViewById(R.id.imageView);
            mTextView1 = itemView.findViewById(R.id.textView);
            mTextView2 = itemView.findViewById(R.id.textView2);
            mButton = itemView.findViewById(R.id.mybutton);


        }
    }

    public ExampleAdapter(ArrayList<ExampleItem> exampleList)
    {

        mExampleList = exampleList;

    }

    @NonNull
    @Override
    public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
        ExampleViewHolder evh = new ExampleViewHolder(v);
        return evh;

    }

    @Override
    public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {

        ExampleItem currentItem = mExampleList.get(position);
        holder.mImageView.setImageResource(currentItem.getImageResource());
        holder.mTextView1.setText(currentItem.getText1());
        holder.mTextView2.setText(currentItem.getText2());

holder.mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              clickCallback.onItemClick(position, holder.mImageView);
            //and same for other views
             }

    }

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

    }


    public interface ClickCallback{
        void onItemClick(int position, View view);
         //here you can send the object of the list at the position if you require 
         //that in activity

    }
}

Hope you got the answer. Happy Coding :)




回答4:


This code shows an Dialog on each item clicked

@NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.recycler_item, null);
        final ItemViewHolder viewHolder = new ItemViewHolder(view);
        dialoge = new Dialog(parent.getContext());
        dialoge.setContentView(R.layout.dialog);
        dialoge.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        viewHolder.container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setDialog(dialoge, viewHolder);
                dialoge.show();
            }

        });

        return viewHolder;
    }

and in the methode setDialog() you get the current item position by using

final RecyclerItem currentItem = itemList.get(viewHolder.getAdapterPosition());

But i think the best practice is to consider using an inerface and here is a good tutorial to follow tutorialRecyclerItemOnClickListenerInterface

I hope this helps you

EDIT : Start an activity from the onClickListnere :

Intent myIntent = new Intent(parent.getContext(),yourActivityName.class);
                myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(myIntent);


来源:https://stackoverflow.com/questions/57919040/how-to-add-functionality-to-buttons-of-each-of-the-recyclerview-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!