How to to set onClick in the RecyclerView? - android

I have created a RecyclerView Adapter but now i'm struggling to do the onClick to open new activity.
This is my RecyclerView Adapter class:
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
private ArrayList<HashMap<String, String>> mDataset;
Context ctx;
public RecycleAdapter(ArrayList<HashMap<String, String>> mDataset) {
this.mDataset = mDataset;
this.ctx = ctx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_procedure, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.getId().setText(mDataset.get(position).get("id"));
holder.getItemname().setText(mDataset.get(position).get("name"));
//holder.getIvImage().setBackground(mDataset.get(position).get("icon"));
}
#Override
public int getItemCount() {
return mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CardView cardView;
private TextView itemId;
private TextView tvName;
private ImageView ivImage;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemId = itemView.findViewById(R.id.tvProfileItemName);
tvName = itemView.findViewById(R.id.tvProfileItemAge);
ivImage = itemView.findViewById(R.id.imageView3);
}
public TextView getId() {
return itemId;
}
public TextView getItemname() {
return tvName;
}
public ImageView getIvImage() {
return ivImage;
}
#Override
public void onClick(View v) {
}
}
}
My Main Activity just display the data inside of a recycler view
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{"id", "name", "icon"},
new int[]{R.id.id, R.id.name, R.id.icon});
mAdapter = new RecycleAdapter(contactList);
mRecyclerView.setAdapter(mAdapter);
}

use interface
in recycler view adapter class
public interface recClick{
void onClickRec(int p);
}
private recClick rc;
public void setRecClick(recClick rc){
this.rc = rc
}
in recycler view holder class
#Override
public void onClick(View v) {
rc.onClickRec(getAdapterPosition());
}
in MainActivity use Interface
class MainActivity implements AdapterClass.recClick{
mAdapter.setRecClick(this);
#Override
public onClickRec(int p)
{
// do someting
}
}

#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int pos =position;
holder.getId().setText(mDataset.get(position).get("id"));
holder.getItemname().setText(mDataset.get(position).get("name"));
//holder.getIvImage().setBackground(mDataset.get(position).get("icon"));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,NewActivity.class);
intent.putExtra("yourValue", String.valueOf(mDataset.get(position).get(pos)));
ctx.startActivity(intent);
}
});
}
Remember to give reference to your cardview
cardView = (CardView)itemView.findViewById(R.id.cardview);

Related

Why does this onClickListener give a NullPointerException?

In activity
borderFav = (Button) findViewById(R.id.borderFav);
fav = (Button) findViewById(R.id.fav);
borderFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
borderFav.setVisibility(View.GONE);
fav.setVisibility(View.VISIBLE);
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fav.setVisibility(View.GONE);
borderFav.setVisibility(View.VISIBLE);
}
});
In XML of a RecyclerView item
<Button
android:id="#+id/borderFav"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="10"
android:layout_gravity="center"
android:background="#drawable/favorite_border_24"
android:visibility="visible"
/>
<Button
android:id="#+id/fav"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="10"
android:layout_gravity="center"
android:background="#drawable/favorite_24"
android:visibility="gone"
/>
Logic is simple, empty heart gets clicked, turns into full heart, full heart clicked turns into empty heart, but Logcat gives a NullPointer in the activity.
If I remove the onClickListeners for those two, there is no error.
RecyclerView Adapter code
public class AllAdapter extends RecyclerView.Adapter<AllAdapter.ViewHolder> {
private ArrayList<Food> data;
private OnItemListener onItemListener;
public ArrayList<Food> getData() {
return data;
}
public AllAdapter(ArrayList<Food> data, OnItemListener onItemListener) {
this.data = data;
this.onItemListener = onItemListener;
}
#NonNull
#Override
public AllAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(v, onItemListener);
}
#Override
public void onBindViewHolder(#NonNull AllAdapter.ViewHolder holder, final int position) {
holder.textView.setText(this.data.get(position).getName());
}
#Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView textView;
private OnItemListener onItemListener;
public ViewHolder(#NonNull View itemView, OnItemListener onItemListener) {
super(itemView);
this.textView = itemView.findViewById(R.id.tv);
this.onItemListener = onItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemListener.onClick(getAdapterPosition());
}
}
public void filterList(ArrayList<Food> filteredList){
data = filteredList;
notifyDataSetChanged();
}
public interface OnItemListener{
void onClick(int position);
}
}
I did not touch the Adapter to implement the favourite button.
Change your adapter to this and see if it works,
public class AllAdapter extends RecyclerView.Adapter<AllAdapter.ViewHolder> {
private ArrayList<Food> data;
private OnItemListener onItemListener;
public ArrayList<Food> getData() {
return data;
}
public AllAdapter(ArrayList<Food> data, OnItemListener onItemListener) {
this.data = data;
this.onItemListener = onItemListener;
}
#NonNull
#Override
public AllAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(v, onItemListener);
}
#Override
public void onBindViewHolder(#NonNull AllAdapter.ViewHolder holder, final int position) {
holder.textView.setText(this.data.get(position).getName());
holder.borderFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.borderFav.setVisibility(View.GONE);
holder.fav.setVisibility(View.VISIBLE);
}
});
holder.fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.fav.setVisibility(View.GONE);
holder.borderFav.setVisibility(View.VISIBLE);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textView;
private Button borderFav, fav;
private OnItemListener onItemListener;
public ViewHolder(#NonNull View itemView, OnItemListener onItemListener) {
super(itemView);
textView = itemView.findViewById(R.id.tv);
borderFav = itemView.findViewById(R.id.borderFav);
fav = itemView.findViewById(R.id.fav);
this.onItemListener = onItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemListener.onClick(getAdapterPosition());
}
}
public void filterList(ArrayList<Food> filteredList) {
data = filteredList;
notifyDataSetChanged();
}
public interface OnItemListener {
void onClick(int position);
}
}
From the code you have pasted it seems, you are doing it wrong, the xml items of recyclerview belongs to the recyclerview adapter so you should place those click listeners in your onBindViewHolder() rather than inside activity.

How can i fix my problem with RecyclerView and OnClickAdapter?

Sorry, i have a problem, i have created ad adapter for a recyclerView to click on one of my item but it doesn't work, it is very frustrating, do you have any ideas?
I have used it in a old application and it works properly but now i don't know why it doesn't work...
Here is my adapter:
public class TecniciAdapter extends RecyclerView.Adapter<TecniciAdapter.MyViewHolder> {
private Context mContext;
private List<Utenti> tecniciList;
private OnTecniciListner onTecniciListner;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView nome;
public TextView cognome;
public TextView stato;
public OnTecniciListner onTecniciListner;
public MyViewHolder(View view, OnTecniciListner onTecniciListner) {
super(view);
nome = view.findViewById(R.id.textNome);
cognome = view.findViewById(R.id.textCognome);
stato = view.findViewById(R.id.textCurrentState);
this.onTecniciListner = onTecniciListner;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onTecniciListner.onTecniciClick(getAdapterPosition());
}
}
public TecniciAdapter(Context context, ArrayList<Utenti> list, OnTecniciListner onTecniciListner) {
this.mContext = context;
this.tecniciList = list;
this.onTecniciListner = onTecniciListner;
}
#NonNull
#Override
public TecniciAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext)
.inflate(R.layout.technician_item, viewGroup, false);
return new TecniciAdapter.MyViewHolder(view, onTecniciListner);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.nome.setText(tecniciList.get(i).getNome());
myViewHolder.cognome.setText(tecniciList.get(i).getCognome());
myViewHolder.stato.setText(tecniciList.get(i).getStato());
}
#Override
public int getItemCount() {
return tecniciList.size();
}
public interface OnTecniciListner{
void onTecniciClick(int position);
}
}
and this is the part in the fragment:
TecniciAdapter adapter = new TecniciAdapter(getActivity(), tecniciList, TecniciFragment.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
I have also this in my fragment:
#Override
public void onTecniciClick(int position) {
Utenti tecnici = tecniciList.get(position);
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
You do not need to create an instance of OnTecniciListner in your ViewHolder class, the one in the TecniciAdapter should work just fine.
So your MyViewHolder class should look like this
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView nome;
public TextView cognome;
public TextView stato;
public MyViewHolder(View view) {
super(view);
nome = view.findViewById(R.id.textNome);
cognome = view.findViewById(R.id.textCognome);
stato = view.findViewById(R.id.textCurrentState);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onTecniciListner.onTecniciClick(getAdapterPosition());
}
}
in onBindViewHoldertry this :
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

Android RecyclreView OnCLick Listener

Error on android recyclerView Adapter. App will stop working while click on RecyclerView items. I want to go other activity when click any items, when i'm using Toast it working fine but if i add Intent then it stop working.
Here is my Interface :
public interface OnItemClickListener {
void onClick(View view, int position);
}
here is my recycler Adapter calss :
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {
private List<Items> items;
private Context context;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.setClickListener(new OnItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView countryname, rank;
ImageView flag;
private OnItemClickListener clickListener;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Add click listener like this:-
View itemView;
Context context;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
this.context=parent.getContext();
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
copying an answer of mine from a different question:
as you already know this method is no longer available in the RecyclerView class.
My approach towards implementing onClick events in a RecyclerView is something like this:
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
interface OnClickListener {
void onClick(Item item);
}
private final List<Item> dataset;
private final OnClickListener l;
public MyAdapter(List<Item> data, OnClickListener listener) {
this.dataset = data;
this.l = listener;
}
#Override MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = //inflate layout
MyClick click = new MyClick() {
onClick(int position) {
if (l != null) {
l.onClick(dataset.get(position));
}
}
};
return new MyViewHolder(click, v);
}
static class MyViewHolder {
final MyClick l;
public MyViewHolder(MyClick listener, View view) {
super(view);
l = listener;
// inflate views
view.setOnClickListener(new OnClickListener() {
if (l != null) {
l.onClick(getAdapterPosition());
}
});
}
interface MyClick {
void onClick(int position);
}
}
}
class MyActivity extends AppCompatActivity {
#Override void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
MyAdapter adapter = new MyAdapter(getData(), new OnClickListener() {
#Override onClick(Item item) {
// do stuff with item
}
});
}
}
You can not click an holder directly..... give a id to the view then re write the code as below:
holder.(someitem).setClickListener(new OnItemClickListener() {//you need a view to execute the onclicklistener
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
Here is code which i create click listener for Recycler Item Click
Using this you will get two types of click
Simple Item click.
Item Long click.
Here is RecyclerItemClickListener.java File
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener
{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
#Override
public void onLongPress(MotionEvent e)
{
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null)
{
mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
View childView = view.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
{
mListener.onItemClick(childView, view.getChildPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
How to use in Activity and Fragment
rvcyclerView.addOnItemTouchListener(new RecyclerItemClickListener(context, rvcyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//do you what you want tot do simple click
}
#Override
public void onItemLongClick(View view, int position) {
//do you what you want tot do on long click
}
}));
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> implements View.OnClickListener {
private List<Items> items;
private Context context;
private OnItemClickListener clickListener;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.flag.setOnClickListener(this);
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView countryname, rank;
ImageView flag;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
On Your Activity / Fragment Implement OnItemClickListener
public class MainActivity extends AppCompatActivity implements OnItemClickListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayoutManager layout = new
LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layout );
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
RecAdapter adapter = new RecAdapter(items ,getContext());
adapter.setClickListener(this);
mRecyclerView.setAdapter(adapter );
}
#Override
public void onClick(View view, int position) {
switch(view.getId()) {
}
}
}

Android RecyclerView onClick in different Activity

Everything works well and my onClick in my recyclerView is working in getting the positions of my items, but what my design calls for is to be able to click an item of the recyclerView and open up a new activity (as a popover or pop up). I can achieve this but my problems comes with the information I need to display on the popover. The information comes like this inside the activity (inside a Firebase value call)
attributeList.removeAll(attributeList);
for (DataSnapshot child : dataSnapshot.child("Attribute").getChildren()){
Attribute attribute = child.getValue(Attribute.class);
attribute_list newAttributeList = new attribute_list( attribute.Name + ": " + attribute.Value);
attributeList.add(newAttributeList);
}
attributeAdapter = new attribute_list_adapter(attributeList, getContext());
recyclerAttribute.setAdapter(attributeAdapter);
This works perfectly for displaying the information, but there's more then just a "value" and a "name" associated with the click.
Basically when I select an item, I need to get the position of the item clicked (which I have) and compare it to the position inside attributeList so I can call a Firebase call (or pass the data somehow) to the popover to display values from the "Attribute" class (such as Name, Value, Description, and another list (recyclerView).
My recyclerView:
public class attribute_list_adapter extends RecyclerView.Adapter<attribute_list_adapter.ViewHolder> {
private List<attribute_list> listItems;
private Context context;
public attribute_list_adapter(List<attribute_list> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.attribute_list, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
attribute_list listItem = listItems.get(position);
holder.txtTitle.setText(listItem.getTxtTitle());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtTitle;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
}
#Override
public void onClick(View v) {
}
}
}
This is example:
public class attribute_list_adapter extends RecyclerView.Adapter<attribute_list_adapter.ViewHolder> {
private List<attribute_list> listItems;
private Context context;
public attribute_list_adapter(List<attribute_list> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.attribute_list, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtberita;
ImageView imgberita;
TextView txtnama;
public ViewHolder(View itemView) {
super(itemView);
txtnama = (TextView) itemView.findViewById(R.id.txtnama);
txtberita = (TextView) itemView.findViewById(R.id.txtberita);
imgberita = (ImageView) itemView.findViewById(R.id.imgberita);
}
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
OnItemClickListener onItemClickListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
}
your Activity. in Oncreate()
public class TestActivity extends AppCompatActivity implements attribute_list_adapter.OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
attribute_list_adapter adapter = new attribute_list_adapter(listItems, this);
adapter.setOnItemClickListener(this);
}
#Override
public void onItemClick(int position) {
// code here
}
}
Create an interface something like
public interface OnSingleItemClickListener{
void onSingleItemClick(int position);
}
Then implement it on your ViewHolder like this
public class ViewHolder extends RecyclerView.ViewHolder implements OnSingleItemClickListener {
public ViewHolder(View itemView) {
super(itemView);
}
#Override
void onSingleItemClick(int position){
if(listItems.get(position) == listItems.get(getAdapterPosition)){
// TODO do something here
}
}
now on your OnBindViewHolder inside your adapter you must do this.
holder.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
holder.onSingleItemClick(position);
}
}):

Cardview click event is not working on android?

I show list of data in card view successfully but now i want to open another activity and show details of clicked data.
I have three class MainActivity, ContactAdapter, Contact.
Main Activity Code:
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
String[] name,email;
ArrayList<Contact> list = new ArrayList<Contact>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
int count = 0;
for (String Name : name)
{
Contact contact = new Contact(Name,email[count]);
count++;
list.add(contact);
}
recyclerView= (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new ContactAdapter(list);
recyclerView.setAdapter(adapter);
i tried but it's not working.
Adapter Code:
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
ArrayList<Contact> contacts = new ArrayList<Contact>();
public ContactAdapter(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact CON = contacts.get(position);
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
TextView person_name, person_email;
public ContactViewHolder(View view) {
super(view);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "OnClick Version :",
Toast.LENGTH_SHORT).show();
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(v.getContext(), "OnLongClick Version :",
Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}
In your adapter do this:
public class ProdutoAdapter extends RecyclerView.Adapter<ProdutoAdapter.ProdutoViewHolder>{
private static ProdutoAdapter.ClickListener clickListener; //this is important
private List<Produto> produtos; //this is my list of beans
public ProdutoAdapter(List<Produto> produtos) {
this.produtos = produtos;
}
#Override
public ProdutoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_produtos, parent, false);
ProdutoViewHolder mvh = new ProdutoViewHolder(v);
return mvh;
}
#Override
public void onBindViewHolder(ProdutoViewHolder holder, int position) {
//holder.nome.setText(this.produtos.get(position).getNome());
holder.img.setImageDrawable(produtos.get(position).getImgDrawable());
holder.nome.setText(produtos.get(position).getNome());
holder.preco.setText(String.valueOf(produtos.get(position).getPreco()));
}
#Override
public int getItemCount() {
return this.produtos.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ProdutoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
Produto produto;
CardView cardView;
TextView nome;
TextView preco;
ImageView img;
ProdutoViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
cardView = (CardView) itemView.findViewById(R.id.cardviewProduto);
nome = (TextView) itemView.findViewById(R.id.nome);
preco = (TextView) itemView.findViewById(R.id.preco);
img = (ImageView) itemView.findViewById(R.id.foto);
}
public void setItem(Produto produto){
this.produto = produto;
}
public Produto getItem(){
return this.produto;
}
//this is what you'll need in your activity
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
#Override
public boolean onLongClick(View v) {
clickListener.onItemLongClick(getAdapterPosition(), v);
return false;
}
}
public void setOnItemClickListener(ClickListener clickListener){
ProdutoAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
void onItemLongClick(int position, View v);
}
}
and in your activity:
public static ProdutoAdapter mAdapter;
myActivity.mAdapter.setOnItemClickListener(new ProdutoAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
//do what you want
}
#Override
public void onItemLongClick(int position, View v) {
}
});
myActivity.mRecyclerView.setAdapter(mAdapter);

Categories

Resources