I have created a recyclerView in my android project.I have 11 items.Each one consists of an imageview and two textviews.When I Click on any of the items it should go to their corressponding activity.How do I accomplish that.Below is the code of my recyclerView adapter.Please help me.
RecyclerAdapter.java:
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.TextView;
/**
* Created by Sabudaniel61 on 2015-10-15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
HotelData[] hoteldata;View view;
RecyclerAdapter(HotelData[] hoteldata){
this.hoteldata=hoteldata;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerlayout,null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.imageView.setImageResource(hoteldata[i].getImageUrl());
viewHolder.textView1.setText(hoteldata[i].getHotel());
viewHolder.textView2.setText(hoteldata[i].getPlace());
}
#Override
public int getItemCount() {
return hoteldata.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView textView1,textView2;ImageView imageView;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
textView1=(TextView) itemLayoutView.findViewById(R.id.textView1);
textView2=(TextView) itemLayoutView.findViewById(R.id.textView2);
imageView=(ImageView) itemLayoutView.findViewById(R.id.imageView1);
}
}
}
In your RecyclerAdapter make a onclicklistener.
private final OnClickListener mOnClickListener = new MyOnClickListener();
#Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int position) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerlayout,null);
view.setOnClickListener(mOnClickListener);
return new MyViewHolder(view);
}
The onClick method:
#Override
public void onClick(final View view) {
int itemPosition = mRecyclerView.getChildPosition(view);
String item = mList.get(itemPosition);//if you want to pass the data
//Navigate to your desired activity.
}
This is the simplest method.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1,textView2;ImageView imageView;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
textView1=(TextView) itemLayoutView.findViewById(R.id.textView1);
textView2=(TextView) itemLayoutView.findViewById(R.id.textView2);
imageView=(ImageView) itemLayoutView.findViewById(R.id.imageView1);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ContentDetails.class);
itemView.getContext().startActivity(intent);
}
}
try this
You can populate recyclerview like this:
first of all, in your layout, put an id for the linearlayout
<LinearLayout
android:orientation="horizontal"
android:id="#+id/linearView" //add this line
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/imageView1"
android:layout_gravity="top" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView1"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="top"
android:layout_marginLeft="10dp" />
</LinearLayout>
the layout above will be called from your adapter on onCreateViewHolder function.
then, call the linear layout you have created on your viewHolder class:
public class ViewHolder extends RecyclerView.ViewHolder{
TextView textView;ImageView imageView;LinearLayout linearLayout;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
textView1=(TextView) itemLayoutView.findViewById(R.id.textView1);
imageView=(ImageView) itemLayoutView.findViewById(R.id.imageView1);
linearLayout=(LinearLayout) itemLayoutView.findViewById(R.id.linearView);
}
}
finally, set onclicklistener to your recyclerview item like this:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//i use arraylist of type Hotel instead of array
final Hotel hotel = HotelData.get(position);
holder.textView1.setText(hotel.getName());
//if you want to add clicklistener to recyclerview item
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//you can call activity here
}
});
//if you want to add click listener to textview inside recyclerview item
holder.textView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.class,"textview clicked",Toast.LENGTH_LONG).show();
}
});
}
put an interface inside the adapter and call it from activity:
private ArrayList<Inbox> list;
private Activity context;
private onItemClickedListener onItemClickedListener;
public InboxListAdapter(Activity context, ArrayList<Inbox> list) {
this.list = list;
this.context = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name;
private TextView date;
private ImageButton btn_play;
private ImageButton btn_share;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
image = (ImageView) itemLayoutView.findViewById(R.id.image);
name = (TextView) itemLayoutView.findViewById(R.id.name);
date = (TextView) itemLayoutView.findViewById(R.id.date);
}
}
#Override
public InboxListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_inbox_list, parent, false);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
From activity
InboxListAdapter adapter = new InboxListAdapter(getActivity(), list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(adapter);
adapter.setOnItemClickedListener(new InboxListAdapter.onItemClickedListener() {
#Override
public void onItemClicked(Inbox inbox) {
}
});
Related
I know this questions has been asked in the past. For some reason I can't seem to get it to work even though I tried using
understoodLanguageListAdapter.notifyDataSetChanged();
in my Activity file. Here is my code
Fragment file containing RecyclerView.
<android.support.v7.widget.RecyclerView
android:id="#+id/color_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Item layout:
<TextView
android:id="#+id/colorText"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/colorImage"
android:layout_height="wrap_content"
android:clickable="true"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:srcCompat="#drawable/icn_close_bluepurple" />
Adapter code:
public class ColorsListAdapter extends RecyclerView.Adapter {
Context context;
List<String> list;
public ColorsListAdapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colors_item,parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(holder.textView.getText().toString());
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
}
}
}
Activity code is as follows:
RecyclerView recyclerView;
List<String> list;
UnderstoodLanguageListAdapter understoodLanguageListAdapter;
---
---
#Override
protected void initialize(Bundle savedInstanceState) {
recyclerView = (RecyclerView) findViewById(R.id.color_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ColorsManager colorsManager = new ColorsManager();
list = colorsManager.getUnderstoodLanguageList();
colorsListAdapter = new ColorsListAdapter(this, list);
recyclerView.setAdapter(colorsListAdapter);
}
Any advice/tips about the fix is much appreciated.
Thank you!
You should change in adapter class like replace bellow code
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(holder.textView.getText().toString());
}
});
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
}
}
with new code
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(list.get(pos));
notifyItemRemoved(pos);
}
});
}
}
You should try notifyItemRemoved(position)
First of all you have to let adapter know that some changes has been made in certain position, to achieve that you need to use some callback (Listener), which has to be passed from your View -> Adapter -> ViewHolder or something similar.
You are creating new instance of ColorManager every time user clicks ImageView.
This new instance is obviously different from one that you used in initialize().
So, the item in new instance is updated and not the list that you passed to recycler adapter
so I have an android project that makes use of recyclerview and cardview, where I set a background imageview on click of a card. This is my code:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.Viewholder> {
private ArrayList <Integer> mImages = new ArrayList<>();
public RecyclerViewAdapter( Context mContext, ArrayList<Integer> mImages) {
this.mImages = mImages;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemlist,viewGroup,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final Viewholder viewholder, int i) {
viewholder.img.setImageResource(mImages.get(i));
}
#Override
public int getItemCount() {
return mImages.size();
}
public class Viewholder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView img;
ImageView imv;
public Viewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.imgview);
imv = itemView.findViewById(R.id.imageView4);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("TEST", "Clicked");
int position = getLayoutPosition();
imv.setImageResource(R.drawable.vehicles);
}
}
}
But it doesn't work on click and the app just crashes. How do I resolve this issue?
You must define your itemView as clickable for receiving click events.
android:clickable="true"
please try move onClickListener to onBindViewHolder
#Override
public void onBindViewHolder(#NonNull final Viewholder viewholder, int i) {
viewholder.img.setImageResource(mImages.get(i));
viewholder.img.setOnClickListener(v -> {
// your code
});
}
Please try
itemView.setOnClickListener(new View.OnClickListener{
#Override
public void onClick(View view){
//your code
}
});
I'm creating an app with a Recyclerview having a Textview and a Button for each item. Initially, all the Textviews will be invisible. I want it to be visible when the corresponding button gets pressed. I managed to make this but it has a problem.
Here's a simplified version of my code:
MainActivity.java:
package com.example.so;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private WordListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerview);
mAdapter = new WordListAdapter(this);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
WordListAdapter.java:
package com.example.so;
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.Button;
import android.widget.TextView;
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
private LayoutInflater mInflator;
public WordListAdapter(Context context) {
mInflator = LayoutInflater.from(context);
}
class WordViewHolder extends RecyclerView.ViewHolder {
private final TextView itemTextview;
private final Button itembutton;
final WordListAdapter mAdapter;
public WordViewHolder(View itemView, WordListAdapter adapter) {
super(itemView);
itemTextview = itemView.findViewById(R.id.item_text);
itembutton = itemView.findViewById(R.id.item_button);
this.mAdapter = adapter;
itembutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemTextview.setVisibility(View.VISIBLE);
}
});
}
}
#NonNull
#Override
public WordListAdapter.WordViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = mInflator.inflate(R.layout.wordlist_item, parent, false);
return new WordViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 20;
}
}
wordlist_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_margin="6dp">
<TextView
android:id="#+id/item_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:layout_weight="1"
android:text="Button clicked!"
android:visibility="invisible"/>
<Button
android:id="#+id/item_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The problem with this is that when I press the first Button, the 15th Textview, in addition to the first Textview becomes visible. Similarly, when I press the 16th button, the 2nd Textview, in addition to the
16th Textview becomes visible. The same goes for other buttons.
I'm not sure why two Textviews become visible when pressing a single button. What's wrong with the code?
When you scroll and new RecyclerView items are being show to you, they are redrawn (recycled) and data is being newly inserted into them, using onBindViewHolder() function.
I would advise you to have some sort a Collection or an Array of visible items and use some logic in the onBindViewHolder() to hide or display them.
The Constructor
private boolean[] visibleItems;
public WordListAdapter(Context context) {
mInflator = LayoutInflater.from(context);
visibleItems = new boolean[20];
}
and the ViewHolder
itembutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
visibleItems[pos] = true;
notifyItemChanged(pos);
}
});
and the onBindViewHolder()
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, int position) {
if(visibleItems[position])
itemTextview.setVisibility(View.VISIBLE);
else itemTextview.setVisibility(View.INVISIBLE);
}
The same problem you have happens if there are EditTexts in the RecyclerView items and they are not set them using setText() inside the same function, but are only editable.
When you are scrolling in a recycler view, the items are recycled. So create a variable to store the position of the item of which you clicked the button.
Implement in the onBindViewHolder
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, final int position){
holder.itemTextview.setVisibility(View.INVISIBLE);
if(currentPosition == position){
holder.itemTextview.setVisibility(View.VISIBLE);
}
holder.itembutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1){
// TODO: Implement this method
currentPosition = position;
notifyDataSetChanged();
}
});
}
The class WordListAdapter will look like this.
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder>
{
private Context context;
private static int currentPosition=0;
public WordListAdapter(Context context){
this.context = context;
}
class WordViewHolder extends RecyclerView.ViewHolder
{
private final TextView itemTextview;
private final Button itembutton;
public WordViewHolder(View itemView){
super(itemView);
itemTextview = (TextView)itemView.findViewById(R.id.item_text);
itembutton = (Button) itemView.findViewById(R.id.item_button);
}
}
#NonNull
#Override
public WordListAdapter.WordViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View mItemView = LayoutInflater.from(context).inflate(R.layout.wordlist_item, parent, false);
return new WordViewHolder(mItemView);
}
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, final int position){
holder.itemTextview.setVisibility(View.INVISIBLE);
if(currentPosition == position){
holder.itemTextview.setVisibility(View.VISIBLE);
}
holder.itembutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1){
// TODO: Implement this method
currentPosition = position;
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount(){
return 20;
}
}
Try to implement getItemId() method inside adapter.
#Override
public long getItemId(int position) {
return position;
}
You should assign a visible/hidden status for each item. And change the status when the button clicked.
And in onBindViewHolder() you should use if/else to make the TextView visible/gone. Something like below. data is the array of your items. VisibilityStatus is the status i mentioned above. You can either put it in the data model, or keep it in another Array or SparseBooleanArray.
if (data.getVisibilityStatus(position)) {
itemTextview.setVisibility(View.VISIBLE);
} else {
itemTextview.setVisibility(View.GONE);
}
You need to add this method in your adapter
This method Return the view type of the item at position for the purposes of view recycling.
#Override
public int getItemViewType(int position) {
return position;
}
In adapter
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
private LayoutInflater mInflator;
public WordListAdapter(Context context) {
mInflator = LayoutInflater.from(context);
}
class WordViewHolder extends RecyclerView.ViewHolder {
private TextView itemTextview;
private Button itembutton;
// final WordListAdapter mAdapter;
public WordViewHolder(View itemView) {
super(itemView);
itemTextview = itemView.findViewById(R.id.item_text);
itembutton = itemView.findViewById(R.id.item_button);
}
}
#NonNull
#Override
public WordListAdapter.WordViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = mInflator.inflate(R.layout.wordlist_item, parent, false);
return new WordViewHolder(mItemView);
}
#Override
public void onBindViewHolder(#NonNull final WordListAdapter.WordViewHolder holder, int position) {
holder.itembutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.itemTextview.setVisibility(View.VISIBLE);
}
});
}
#Override
public int getItemCount() {
return 20;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
Extension to Viktor Stojanov's answer:
This behaviour is due to recyclerView's property of "recycling" the views.
When the list is scrolled, the views that become invisible are made eligible for reuse and those views are used again for the items that are about be be shown on the screen.
i.e. the same upper views are used, just the new data is binded using onBindViewHolder().
I would suggest you to maintain an Arraylist of simple POJOs and refer their state to update the views in your recyclerView.
e.g.
public class Word{
private boolean isVisible;
private String content;
//getters and setters for both properties
}
In bindViewHolder check the visibility of item and accordingly show the textView.
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, int position) {
Word currentWord = wordArraylist.get(position);
if(currentWord.getVisibility()){
itemTextView.setText(currentWord.getContent());
itemTextview.setVisibility(View.VISIBLE);
} else{
if(itemTextView.getVisibility != View.INVISIBLE){
itemTextview.setVisibility(View.INVISIBLE);
}
}
}
And in your ViewHolder class you could set the onClickListener on the button to change the visibility, something like this:
itembutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Word currentWord = wordArraylist.get(getAdapterPosition());
if(!currentWord.getVisibility()){
itemTextView.setText(currentWord.getContent());
itemTextview.setVisibility(View.VISIBLE);
}
}
});
i'm searching function that programmatically click method. so i found some method. 'performClick()'
like that :
recyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();
but it dosen't work in my case. I can't find solution. How do i use the performClick in Activity???
my Adapter - ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView virtNo;
private TextView score01;
private TextView score02;
private TextView score03;
private TextView totalScore;
private LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
this.virtNo = (TextView) itemView.findViewById(R.id.tv_virtNo);
this.score01 = (TextView) itemView.findViewById(R.id.tv_score01);
this.score02 = (TextView) itemView.findViewById(R.id.tv_score02);
this.score03 = (TextView) itemView.findViewById(R.id.tv_score03);
this.totalScore = (TextView) itemView.findViewById(R.id.tv_totalScore);
this.linearLayout = (LinearLayout) itemView.findViewById(R.id.ll_item_score);
virtNo.setOnClickListener(this);
score01.setOnClickListener(this);
score02.setOnClickListener(this);
score03.setOnClickListener(this);
score10.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getAdapterPosition(), items.get(getAdapterPosition()));
}
}
public void setOnClickListener(OnClickListener<Score> onClickListener) {
this.onClickListener = onClickListener;
}
public interface OnClickListener<T> {
void onClick(View v, int position, T item);
}
my Adapter - onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Score item = items.get(position);
holder.virtNo.setText(item.virtNo);
holder.score01.setText(item.score01);
holder.score02.setText(item.score02);
holder.score03.setText(item.score03);
holder.totalScore.setText(itemSum(item));
}
}
I have tried to keep things easy to understand here, it is a complete example for listening to click event on individual items in RecyclerView, there are other ways to do it as well. This code works, You may modify it as it fits you, in case you have any question write them in comments. code is also available at GitHub
public class RecyclerViewOneActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_one);
initializeUI();
}
private void initializeUI() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.RecyclerViewOneActivity_RecyclerView);
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
ArrayList<String> strings = new ArrayList<>();
strings.add("first");
strings.add("second");
MyAdapter adapter = new MyAdapter(getApplicationContext(), strings);
recyclerView.setAdapter(adapter);
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> strings;
private LayoutInflater layoutInflater;
public MyAdapter(Context context, ArrayList<String> strings) {
this.context = context;
this.strings = strings;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.single_item_recycler_view_one, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final String text = this.strings.get(position);
holder.textView.setText("" + text);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+text, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return strings.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.single_item_recycler_view_one_linear_layout);
textView = (TextView) itemView.findViewById(R.id.single_item_recycler_view_one_textView);
}
}
}
}
single_item_recycler_view_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="#+id/single_item_recycler_view_one_linear_layout"
android:orientation="vertical">
<TextView
android:id="#+id/single_item_recycler_view_one_textView"
android:layout_width="match_parent"
android:textColor="#000"
android:layout_height="wrap_content"
android:text="Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
I have an array of 600 items. I list down all the array items in a RecyclerView and scrolling well.But when I try to access onClick listener it is not getting. I try to Implement View.OnClickListener and Override onClick.But its not working.
I want to Toast item in the list item when user click one of the row item in the view
Adapter code is
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private String mItem;
private TextView mTextView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
mTextView = (TextView) view.findViewById(R.id.item_title);
}
public void setItem(String item) {
mItem = item;
mTextView.setText(item);
}
#Override
public void onClick(View view) {
Log.d("TAG", "onClick " + getPosition() + " " + mItem);
}
}
private String[] mDataset;
public MyAdapter(String[] dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setItem(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
Can any one please help me
Thanks in advance :)
I have create a sample project using your code onClickListener working fine.Like when i click on item shows me the clicked item position in Log.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
private RecyclerView mRecyclerView;
private String[] dataSet = {"Waleed", "Sarwar", "Yousuf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(dataSet);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
public MyAdapter(String[] dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setItem(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private String mItem;
private TextView mTextView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
mTextView = (TextView) view.findViewById(R.id.item_title);
}
public void setItem(String item) {
mItem = item;
mTextView.setText(item);
}
#Override
public void onClick(View view) {
Log.d("TAG", "onClick " + getPosition() + " " + mItem);
}
}
}
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="56dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
if you are still facing the problem download the sample project from link below.
https://www.dropbox.com/s/xf3y8oxok0zlgxk/RecyclerViewOnClick.zip?dl=0
pls see jcobs ans it may help you
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
})
);
implement your code in onitemclick.
happy coding :)
You can handle it by setting on click listener to your parent view. Recyclerview don't provide you default item click listner same as listview.
So create object of your parent layout and set it click listner.
Your holder initialization.
class UserListHolder extends RecyclerView.ViewHolder {
RelativeLayout layoutMain;
UserListHolder(View itemView) {
layoutMain = (RelativeLayout)itemView.findViewById(R.id.layoutSquadItem);
}
}
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder,final int position) {
((UserListHolder)viewHolder).layoutMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click
}
});
}
You can also refer recycler view on click listner