简体   繁体   中英

onClick in each list of recyclerView

I've set 2 recyclerView in a layout and pass data in that recyclerView using arraylist. I am trying to set clickListener in each array list of different recyclerview.

this is adapter

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder>{
    Context context;
    int LayoutId;
    List<ItemModel> data;

    private OnNoteClickListener mOnNoteClickListener;

    public RecyclerAdapter(Context context, int layoutId, List<ItemModel> data, OnNoteClickListener onNoteClickListener) {
        this.context = context;
        LayoutId = layoutId;
        this.data = data;
        this.mOnNoteClickListener = onNoteClickListener;
    }

    public RecyclerAdapter(MainActivity mainActivity, int item_layout_vertical, List<ItemModel> topRecycleData) {
    }

    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View myView = inflater.inflate(LayoutId,null);
        return new RecyclerViewHolder(myView, mOnNoteClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
        final ItemModel singleItem = data.get(position);
        holder.imgTitle.setText(singleItem.getImgTitle());
        holder.img.setImageDrawable(context.getResources().getDrawable(singleItem.getImgId()));
    }

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

    public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        OnNoteClickListener onNoteClickListener;
        TextView imgTitle;

        ImageView img;
        public RecyclerViewHolder(@NonNull View itemView, OnNoteClickListener onNoteClickListener) {
            super(itemView);
            imgTitle = itemView.findViewById(R.id.imgTitle);
            img = itemView.findViewById(R.id.img);
            this.onNoteClickListener = onNoteClickListener;

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onNoteClickListener.onNoteClick(getAdapterPosition());
        }
    }

    public interface OnNoteClickListener{
        void onNoteClick(int positon);
    }

}

this is activity where recyclerview is shown:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Fetching View From XMl
        topRecyclerView = findViewById(R.id.topRecyclerView);
        bottomRecyclerView = findViewById(R.id.bottomRecyclerView);

        // Data For Top Recycler Views
        List<ItemModel> topRecycleData = new ArrayList<ItemModel>();
        topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1"));
        topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2"));

        // Data For Bottom Recycler Views
        List<ItemModel> bottomRecycleData = new ArrayList<ItemModel>();
        bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1"));
        bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2"));
        bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3"));
        bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4"));


        // Setting Layouts To Recycler Views
        topRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
        bottomRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL,false));

        // Creating Adapters
        RecyclerAdapter topAdapter = new RecyclerAdapter(MainActivity.this,R.layout.item_layout_vertical,topRecycleData);
        RecyclerAdapter bottomAdapter = new RecyclerAdapter(MainActivity.this,R.layout.item_layout_horizontal,bottomRecycleData);

        // Setting Adapters To Layouts
        topRecyclerView.setAdapter(topAdapter);
        bottomRecyclerView.setAdapter(bottomAdapter);

    }

}

If there was a single recyclerview then i hope i could do that but this time there are 2 recyclerview with 2 different arrylist in a home. so i am very confused how to call listener for two different arraylist of recyclerview.

I want to make toast message when clicked in "for example" postion 2 on 1st recycler view and toast message when clicked in position 1 of 2nd recycler view.

Here is the complete code with all the changes. I have tested your code and it runs fine.

MainActivity Java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity{

RecyclerView topRecyclerView, bottomRecyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_main);
    // Fetching View From XMl
    topRecyclerView = findViewById(R.id.topRecyclerView);
    bottomRecyclerView = findViewById(R.id.bottomRecyclerView);

    // Data For Top Recycler Views
    List<ItemModel> topRecycleData = new ArrayList<ItemModel>();
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 5"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 6"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 7"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 8"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 9"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 10"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 11"));
    topRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 12"));


    // Data For Bottom Recycler Views
    List<ItemModel> bottomRecycleData = new ArrayList<ItemModel>();
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 1"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 2"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 3"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 4"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 5"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 6"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 7"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 8"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 9"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 10"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 11"));
    bottomRecycleData.add(new ItemModel(R.mipmap.ic_launcher,"Img 12"));

    // Setting Layouts To Recycler Views
    topRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
    bottomRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    // Creating Adapters (No need to send onNote)
    RecyclerAdapter topAdapter = new RecyclerAdapter
    (this,R.layout.item_layout_vertical,topRecycleData);
    RecyclerAdapter bottomAdapter = new RecyclerAdapter
    (this,R.layout.item_layout_horizontal,bottomRecycleData);

    // Setting Adapters To Layouts
    topRecyclerView.setAdapter(topAdapter);
    bottomRecyclerView.setAdapter(bottomAdapter);
}
}

MainActivity XML Using a Scoll View and Linear Layout with weights on inner linear layouts to scale them equally on screen height. In your code, the top layout was getting hidden by bottom layout. A scroll view must contain a single child, that's why an extra Linear Layout is added as child of Scroll View.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:scrollbars="none"
android:fillViewport="true">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:weightSum="2">

<LinearLayout
    android:layout_margin="5dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CE9D9"
        android:text="Header No 1"
        android:textSize="18sp"
        android:textColor="#000"
        android:padding="5dp"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/topRecyclerView"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


<LinearLayout
    android:id="@+id/bottomRecyclerViewLayout"
    android:layout_margin="5dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CE9D9"
        android:text="Header No 2"
        android:textSize="18sp"
        android:textColor="#000"
        android:padding="5dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/bottomRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
</LinearLayout>
</ScrollView>

item_layout_vertical xml Add an id to the top layout, this will be used to set the onclick listener later.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/verticalContainer"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
    android:id="@+id/img"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher"/>

<TextView
    android:id="@+id/imgTitle"
    android:layout_marginTop="5dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="#000"
    android:textStyle="bold"
    android:text="Hello Dear Dibas"/>

</LinearLayout>

item_layout_horizontal xml Add an id to the top layout, this will be used to set the onclick listener later.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/horizontalContainer"
android:orientation="vertical"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
    android:id="@+id/img"
    android:layout_gravity="center_horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher"/>

<TextView
    android:id="@+id/imgTitle"
    android:layout_marginTop="5dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="#000"
    android:textStyle="bold"
    android:text="Hello Dear Dibas"/>

</LinearLayout>

RecyclerAdapter Java

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;

public class RecyclerAdapter extends 
RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder>{

Context context;
int LayoutId;
List<ItemModel> data;


public RecyclerAdapter(Context context, int layoutId, List<ItemModel> data) {
    this.context = context;
    LayoutId = layoutId;
    this.data = data;
}

@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int 
viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View myView = inflater.inflate(LayoutId,null);
    return new RecyclerViewHolder(myView);
}

@Override
public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int 
position) {
    final ItemModel singleItem = data.get(position);
    holder.imgTitle.setText(singleItem.getImgTitle());
    holder.img.setImageDrawable(context.getResources()
   .getDrawable(singleItem.getImgId()));

   //checking which layout is in layoutId and adding onclick listener
    if (LayoutId == R.layout.item_layout_horizontal)
    {
        holder.horizontalLayout.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) {
                //check which item is clicked here and proceed
                if(position==0)
                {
                    //do something
                }
                else if(position==1)
                {
                     //do something
                }
                else if(position==2)
                {
                    //do something
                }
                //and so on to the list end

            }
        });
    }

    else {
        holder.verticalLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //check which item is clicked here and proceed
                if(position==0)
                {
                    //do something
                }
                else if(position==1)
                {
                    //do something
                }
                else if(position==2)
                {
                    //do something
                }
                //and so on to the list end

            }
        });
    }

    }

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

public class RecyclerViewHolder extends RecyclerView.ViewHolder{
    TextView imgTitle;
    ImageView img;
    LinearLayout horizontalLayout,verticalLayout;
    public RecyclerViewHolder(@NonNull View itemView) {
        super(itemView);
        imgTitle = itemView.findViewById(R.id.imgTitle);
        img = itemView.findViewById(R.id.img);
        //fetching the container views that are to be attached to the 
        //recycler view and for adding onclick listeners 
        //(because of multiple layouts for the same adapter)
        if(LayoutId==R.layout.item_layout_horizontal)

            horizontalLayout=itemView.findViewById(R.id.horizontalContainer);
        else

            verticalLayout=itemView.findViewById(R.id.verticalContainer);

        }

        } 
}

Hope this helps. It is running fine. Add a toast in the click listener conditions to verify if they are working for the exact position. And important to note that position index starts from 0(first item) to so on.

You are actually doing it right but you're not getting the expected result. therefore, instead of

   ...
   this.onNoteClickListener = onNoteClickListener;

        itemView.setOnClickListener(this);

do this:

itemView.setOnClickListener(new View.OnclickListener){
    @Override
    public void onClick(View v){
        if(onNoteClickListener != null){
           int position = getAdapterPosition();//This will provide you the items 
           //position
           //This is to make sure the 
               //position is valid
           if(position != RecyclerView.NO_POSITION){
                 //finally call the onNoteClickListener.onNoteClick
                  onNoteClickListener.onNoteClick(position)
           }
        }
    }
}

After this, go to your Activity Class and call

adapter.setOnItemClickListener(new OnNoteClickListener ...)

then inside the generated methods, you can handle the click events for example:

adapter.setOnItemClickListener(new OnNoteClickListener(){
     @Override
     public void onItemClick(int position){
         mListItem.get(positio);
         Toast.make(getApplicationContext(), "Item Clicked ", 
                   Toast.LENGTH_SHORT).show();
     }
});

That's all. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM