#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String clicktemplate = modelClassesListt.get(i).getTitle();
Toast.makeText(Template.this ,modelClassesListt.get(i).getTitle() , Toast.LENGTH_SHORT).show();
}
I want to send this clicktemplate string value to other class
You have to put value in Intent or Bundle and send it to the next screen.
Here is an example for pass data in Activity.
Intent intent = new Intent(this, YourNextActivity.class);
intent.putExtra("key_clicktemplate", clicktemplate);
startActivity(intent);
To get value in next screen like below
String value = getIntent().getExtras().getString("key_clicktemplate");
You can use several approaches to implement your need.below thread will be useful to you.
How to pass values from RecycleAdapter to MainActivity or Other Activities
In your recyclerview class add onclicklistener interface and include your listener in constructor:
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(myObject item, int position, String message);
}
public MyRecyclerViewAdapter(Activity pActivity, ArrayList<myObject> pList, int pItemLayout, OnItemClickListener listener) {
activity = pActivity;
rewardsList = pList;
layoutID=pItemLayout;
this.listener = listener;
}
Then. in onCreateViewHolder:
#Override
public void onBindViewHolder(MyHolder holder, int position) {
myObject currentItem = rewardsList.get(position);
holder.bindList(currentItem, listener, position);
}
Next, in your ViewHolder add:
class MyHolder extends RecyclerView.ViewHolder {
View masterView;
MyHolder(View itemView) {
super(itemView);
masterView = itemView;
}
void bindList(final myObject item, final OnItemClickListener listener, int position){
masterView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item, position,"edit");
}
});
...
Finally, in calling activity/fragment:
MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(mActivity, list, R.layout.item, new MyRecyclerViewAdapter.OnItemClickListener() {
#Override
public void onItemClick(MyObject item, int position, String message) {
//item clicks handled here
switch (message){
case ITEM_OPEN:
// Do whatever you need with clicked item here
break;
case ITEM_EDIT:
// Do whatever you need with clicked item here
break;
}
}
}, mRecyclerView);
Related
I've created a RecyclerView that gets inflated with an ArrayList of Strings and I want to put extra information in an intent for the next activity to get the information. I can pass the position of the element in the reclyclerview(within the intent), but I also want to send the string value that appears in that element. The layout used by the adapter for the recylcerView has nothing but a TextView for displaying the values in the ArrayList of strings.
The problem is in the Adapter, because I want to be able to put an String as extra information in the intent. And what I have to change is the onItemClick method parameters inside ItemClickListener, but I don't know what to do next.
Here's the Adapter:
Adapter_dishes_rv.java
public class Adapter_dishes_rv extends RecyclerView.Adapter<Adapter_dishes_rv.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
Adapter_dishes_rv(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_simple_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.nameoftypeofdish);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {
return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
I think that all I have to change is just the OnItemClick parameters but then what else?
Here's the layout just in case:
recyclerview_simple_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/nameoftypeofdish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
And then there's the main Activity:
FoodFamilyActivity.java
public class FoodFamilyActivity extends Activity implements Adapter_dishes_rv.ItemClickListener {
Adapter_dishes_rv adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_family);
ArrayList<String> dishesOfAFamily = new String[]{"Sopa de pobre", "Sopa de pescado", "Sopa de sobre"}
RecyclerView recyclerView = findViewById(R.id.FamilyDishes);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter_dishes_rv(this, dishesOfAFamily);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(FoodFamilyActivity.this, DishActivity.class);
intent.putExtra(DishActivity.EXTRA_DISHNO, (int) position);
startActivity(intent);
}
}
If you need anything else tell me, because I really need help with this problem.
You can add the following function to your adapter
public String getDishForPosition(int position) {
if (mData != null && mData.size() > 0) {
return mData.get(position);
}
return null;
}
You are already getting the concerned position using getAdapterPosition(). Using the above function you can get the string from the list .
Change your interface to
public interface ItemClickListener {
void onItemClick(View view, int position,String dishes);
}
Now you have the required string in your activity where you can pass it to Intent
I have a RecyclerView and each CardView contains a TextView and an ImageView. Whenever I click an item, I want to set the image visibility to VISIBLE and to set the previous clicked item image's visibility to INVISIBLE.
This is my Adapter class :
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{
private Context context;
private List<Category> lista;
private LayoutInflater layoutInflater;
private IncomeCategoryActivity activity;
private static final int CATEGORY_REQUEST=6;
private static final int ITEM_EDIT=1;
private static final int ITEM_DELETE=2;
private static final int EDIT_REQUEST=7;
private int current_pos=-1;
public CategoryAdapter(List<Category> lista, Context context, IncomeCategoryActivity activity) {
this.context = context;
this.lista = lista;
this.activity=activity;
layoutInflater=LayoutInflater.from(context);
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=layoutInflater.inflate(R.layout.category_layout, parent, false);
ViewHolder viewHolder=new ViewHolder(view, activity);
return viewHolder;
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(lista.get(position).getUri());
holder.textView.setText(lista.get(position).getCategory());
holder.position = position;
holder.category=lista.get(position);
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return lista.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public ImageView imageView;
public TextView textView;
public ImageView imageViewCheck;
public int position;
public Category category;
public IncomeCategoryActivity activity;
public ViewHolder(View itemView, IncomeCategoryActivity activity) {
super(itemView);
this.activity=activity;
imageView=itemView.findViewById(R.id.customCategoryImageView);
textView=itemView.findViewById(R.id.customCategoryTextView);
imageViewCheck=itemView.findViewById(R.id.customCheckImageView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
String aux=textView.getText().toString();
if(aux=="CATEGORIE NOUĂ"){
Intent intent=new Intent(context, CustomIncomeActivity.class);
activity.startActivityForResult(intent, CATEGORY_REQUEST);
}
else{
imageViewCheck.setVisibility(View.VISIBLE);
int pozitie_check=getLayoutPosition();
Intent intent=new Intent(context, AddIncomeActivity.class);
intent.putExtra("categorie_venit", aux);
intent.putExtra("position_check", pozitie_check);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Selectează acțiunea");
MenuItem edit=menu.add(0, ITEM_EDIT, 0, "Modifică");
MenuItem delete=menu.add(0, ITEM_DELETE, 0, "Șterge");
edit.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
int position=getLayoutPosition();
if (item.getGroupId() == 0) {
if(item.getItemId()==ITEM_EDIT){
Category category=lista.get(position);
Intent intent=new Intent(activity, CustomIncomeActivity.class);
intent.putExtra("edit_icon", category.getUri());
intent.putExtra("edit_category", category.getCategory());
intent.putExtra("list_position", position);
activity.startActivityForResult(intent, EDIT_REQUEST);
}
else if(item.getItemId()==ITEM_DELETE){
lista.remove(position);
notifyDataSetChanged();
}
}
return true;
}
At this moment, whenever I click an item, there are two images VISIBLE on the RecyclerView: the clicked item's image and the previous clicked item's image. I think I need to get the previous View by its position and to manually set the visibility to INVISIBLE.
recycleView.getChildCount() and recycleView_parent.getChildAt() only gives the Adapter items which is shows only screen .
that means if your list has 200 items and the only 5 items shows on screen so we can find only 5 item with the help of recycleView
i am using one simple trick to solve the issue.
You can define Hashmap which hold your holder objects
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<Model> dataList;
Context context;
HashMap<Integer,ViewHolder> holderlist;
public MyAdapter(ArrayList<Model> dataList, Context context) {
this.context = context;
this.dataList = dataList;
holderlist = new HashMap<>();
}
And after that to save the holder in Hashmap
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(!holderlist.containsKey(position)){
holderlist.put(position,holder);
}
Create a method in Adapter.
public MyListAdapter.ViewHolder getViewByPosition(int position) {
return holderlist.get(position);
}
Call this method from your Activity or whenever you want.
for (int i = 0; i < datalList.size(); i++) {
MyAdapter.ViewHolder holder = ((MyAdapter)recycleView.getAdapter()).getViewByPosition(i);
View view = holder.itemView;
TextView tv = view.findViewById(R.id.tv);
}
I have created the demo you can refer it and implement for single selection
recyclerView.setAdapter(new RecyclerView.Adapter() {
int selected_position = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.row_color_list,parent,false)) {
#Override
public String toString() {
return super.toString();
}
};
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.image);
if(selected_position == position){
imageView.setVisibility(View.VISIBLE);
}else {
imageView.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected_position != holder.getAdapterPosition()){
selected_position = holder.getAdapterPosition();
notifyDataSetChanged();
}
}
});
}
#Override
public int getItemCount() {
return 20;
}
});
You can do as following:
1) Declare a global variable:
private int selectedPos = -100; // Put any irrelevant number you want
2) Set selected position onClick() :
#Override
public void onClick(View v) {
selectedPos = getAdapterPosition();
}
3) Check selected postion and assign visibility inside onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if(position == selectedPos){
holder.imageViewCheck.setVisibility(View.VISIBLE);
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
Try this code..
add this code into adapter class for handling click event..
OnItemClick onItemClick;
public void setOnItemClick(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
public interface OnItemClick {
void getPosition(String data); //pass any data to shared it.
}
after bind method..
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
// below code handle click event on recycler view item.
final String str=mStringList.get(position); // here your boject
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.getPosition(str); // pass your data.
}
});
}
after bind adapter into recycler view it means adapter not null then called below code..
adpater.setOnItemClick(new RecyclerViewAdpater.OnItemClick() {
#Override
public void getPosition(String data) {
// hear update your value for check into if condition.
data="sdfsdf";
adpater.notifyDataSetChanged();
}
});
and also read comments and also try to make custon class and access that object value and update after click it..
this code only how to handle click event into recycler view.
How to get the position for clicked button inside the RecyclerView items
Here's my onBindViewHolder :
public void onBindViewHolder(MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
//if you need position, just use recycleViewHolder.getAdapterPosition();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});
}
If you need in onBindViewHolder only then you can use
holder.getAdapterPosition();
and if you need this position clicked in activity and fragment then you have to use callbacks from holder to activity and fragment and have to pass the same getAdapterPosition();
Edit: Added sample code for listening position click in fragment/activity
step 1: make an interface or callback
public interface RecyclerViewClickListener {
void onClick(View view, int position);
}
step 2: While initializing adapter class in fragment or activity pass the above-created reference as a parameter
public YourAdapter(List<SomeModel> modelList, RecyclerViewClickListener listener){
this.clickListener = listener;
}
step 3: In your ViewHolder or similar Class for view initialization do something like this
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button mapBtn;
ViewHolder(View v, RecyclerViewClickListener listener) {
super(v);
mapBtn = findViewById(R.id.mapBtn);
mListener = listener;
mapBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mListener.onClick(view, getAdapterPosition());
}
}
you will get the position in your fragment or activity where you have passed the callback reference while initializing the adapter.
Use holder.getAdapterPosition();
public void onBindViewHolder(final MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
Toast.makeText(getContext(), "The position is: "+holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});}
I have a RecyclerView which contains multiple item types (4 or 5 at least).
Some items can be clicked, sometimes they have two differents clickListener (for example two imageView in one item).
For now, the item manages the clicks himself like this :
item.imageView1.setOnClickListener(....){
startActivity(Activity2);
}
item.imageView2.setOnClickListener(....){
startActivity(Activity1);
}
But I have a problem : I need to put some variables in the activity which will be started, so what is the best way to do this :
1) My item need to know these variables and continues to manage his own click ?
2) My item has a listener which call startActivity with the variables (like the fragment or parent activity or an object dedicated to this) ?
If you need more precisions, ask me.
Thx.
Make an interface for passing those values.
public interface MyRecyclerCallback {
void onItemClicked(Integer o); //insert whatever you want to pass further, possibly translated to form packable to intents
}
Then add it to your adapter from the activity with recycler like you would any listener. Either constructor or by separate method.
Pass it further down to every children upon their creation.
Call it when onClick gets detected with appropriate argument.
The actual argument may be some abstract thing
depending on your logic. It's more of a general idea. That's the way I do it with my recyclers.
In your activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
MyAdapter adapter = new MyAdapter(this,new MyRecyclerCallback() {
#Override
public void onItemClicked(Integer o) { //any argument you like, might be an abstract
Intent i = new Intent(this,ActivityTwo.class);
i.putExtra(EXTRA_VALUE,o);
startActivity(i);
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter);
}
Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Child>{
private final Context mContext;
private final MyRecyclerCallback mCallback;
private List<Integer> mChildren;
public MyAdapter(Context ctx, MyRecyclerCallback myRecyclerCallback) {
mContext = ctx;
mCallback = myRecyclerCallback;
mChildren = new ArrayList<>();
}
public void populateList(List<Integer> list ) { //this can be a network call or whatever you like
mChildren.addAll(list);
}
#Override
public Child onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
return new Child(v,mCallback);
}
#Override
public void onBindViewHolder(Child holder, int position) {
holder.setValue1(mChildren.get(position)*3);
holder.setValue2(mChildren.get(position));
}
#Override
public int getItemCount() {
return mChildren.size();
}
public class Child extends RecyclerView.ViewHolder{
View mView1;
View mView2;
private int mValue1;
private int mValue2;
public Child(View itemView, final MyRecyclerCallback mCallback) {
super(itemView);
mView1 = itemView.findViewById(R.id.view1);
mView2 = itemView.findViewById(R.id.view2);
mView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onItemClicked(mValue1);
}
});
mView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onItemClicked(mValue2);
}
});
}
public void setValue1(int position) {
mValue1 = position;
}
public void setValue2(int position) {
mValue2=position;
}
}
}
this a good alternative to handle onclick and onlongclick
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
You can have a single OnClickListener on your ViewHolder class and use it with an interface to determine the type of item which has been clicked.
For example, say you have a model class called Item :
public class Item {
private int itemType;
private String itemDescription;
private String optionalExtra;
public static final int ITEM_TYPE_1 = 1;
public static final int ITEM_TYPE_2 = 2;
public Item(int itemType, String itemDescription) {
this.itemType = itemType;
this.itemDescription = itemDescription;
}
public Item(int itemType, String itemDescription, String optionalExtra) {
this.itemType = itemType;
this.itemDescription = itemDescription;
this.optionalExtra = optionalExtra;
}
}
You have a custom interface defined to intercept click on items in recyclerview :
public interface CustomClickListener {
void onClickOfItemType1( int position );
void onClickOfItemType2( int position );
}
Inside your adapter for recyclerview, in the viewholder class :
//Similar implementation for other ViewHolders too.
public class ViewHolderType1 extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imageView;
TextView textView;
View itemView;
public ViewHolderType1(View view) {
super(view);
this.itemView = view;
//initialize other views here
//Set item click listener on your view
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int itemPosition = getAdapterPosition();
if( itemPosition != RecyclerView.NO_POSITION ) {
customClickListener.onClickOfItemType1(itemPosition);
//You can call onClickOfItemType2(itemPosition) in your other type of view holder class
}
}
}
In your Activity or Fragment :
Pass the customClickListener as a parameter to your adapeter :
CustomAdapter customAdapter = new CustomAdapter(List<Item> itemList, new CustomClickListener {
#Override
void onClickOfItemType1(int position) {
Item item = itemList.get(position);
//This item is of type 1
//You can implement serializable / parcelable in your item class and use it to directly pass across item to your activity
Intent intent = new Intent(Activity.this, CustomActivity1.class);
intent.putExtra("item", item);
startActivity(intent);
}
#Override
void onClickOfItemType2(int position) {
Item item = itemList.get(position);
//This item is of type 2
//You can implement serializable / parcelable in your item class and use it to directly pass across item to your activity
Intent intent = new Intent(Activity.this, CustomActivity2.class);
intent.putExtra("item", item);
startActivity(intent);
}
});
In case you are trying to trigger different activities on click of different views; inside your viewclicklistener implementation check the view id and trigger the corresponding activity.
#Override
public void onClick(View v) {
int itemPosition = getAdapterPosition();
if( itemPosition != RecyclerView.NO_POSITION ) {
switch(v.getId()) {
case R.id.imageView :
customClickListener.onClickOfItemType1(itemPosition);
break;
case R.id.textView :
customClickListener.onClickOfItemType2(itemPosition);
break;
}
}
}
This is a guide for usage of RecyclerView :
https://guides.codepath.com/android/using-the-recyclerview
I have created a interface for extending functionality of Recycler View and making possible to listen click on every item of list, but i can't make it to work. Nothing happens when i click on any item. Here is my code:
// METHOD FOR INITIALIZATION OF RECYCLER VIEW
public void initRecyclerView() {
// SETTING ARRAY FOR CATEGORIES
final CategoryItem categoryItem[] = { new CategoryItem("Birthday", R.drawable.birthday_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image),
new CategoryItem("Anniversary", R.drawable.anniversary_image)};
// FINDING RECYCLER VIEW IN LAYOUT
recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
adapter = new CategoriesListAdapter(categoryItem);
recyclerView.setAdapter(adapter);
// SETTING ON CLICK LISTENER ON ADAPTER
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void setOnItemClick(View view, int position) {
String clickedItem = String.valueOf(position);
if ( clickedItem.equals("Birthday") ) {
Toast.makeText(MainActivity.this, "Clicked on Birthday!", Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
UPDATE:
adapter
public class CategoriesListAdapter extends RecyclerView.Adapter<CategoriesListAdapter.ViewHolder> {
private CategoryItem[] categoryItems;
private static OnItemClickListener onItemClickListener;
public CategoriesListAdapter(CategoryItem[] categoryItems) {
this.categoryItems = categoryItems;
}
#Override
public CategoriesListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
viewHolder.txtViewTitle.setText(categoryItems[position].getTitle());
viewHolder.imgViewIcon.setImageResource(categoryItems[position].getImage());
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.image);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemClickListener.setOnItemClick(v, getAdapterPosition());
}
}
public void setOnItemClickListener (final OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
// Return the size of your itemsData (invoked by the layout manager)
#Override
public int getItemCount() {
return categoryItems.length;
}
}
INTERFACE:
public interface OnItemClickListener {
public void setOnItemClick(View view, int position);
}
It should display toast message if birthday is selected, but it's not displaying anything. I'm instancing array of class and i don't know how to listen clicked item. The answers there didn't help me solving my problem.
Currently you are checking your position against string "Birthday" in OnItemClickListener method setOnItemClick
String clickedItem = String.valueOf(position);
if ( clickedItem.equals("Birthday") ) {
...
}
which never gonna be true. Try getting item for position and checking its first parameter against "Birthday" or bring your Toast out from that if statement and just print out position number for beginning to understand what's going on in there
#Override
public void setOnItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked item on position: " + position, Toast.LENGTH_SHORT).show();
}
My Solution:
Steps Involved
Created an interface RecyclerviewClickListener
Implemented interface on an activity/fragment
Passed the interface to the adapter
Called an interface method on an item clicked onBindViewHolder.
RecyclerviewClickListener interface
//Created an interface RecyclerviewClickListener
public interface RecyclerviewClickListener
{
void recyclerviewClickListener(int position);
}
NewFragment
//Implemented interface on an activity/fragment
public class NewFragment extends Fragment implements RecyclerviewClickListener
{
//Passed the interface to the adapter
adapter = new Adapter(getContext(), dataList, this);
#Override
public void recyclerviewClickListener(int position)
{
//Do something here with the position from a recyclerview
//e.g dataList.get(position);
}
}
Adapter
public class UniversityAdapter extends RecyclerView.Adapter<UniversityAdapter.ViewHolder>
{
private final ArrayList<User> dataList;
private final Context context;
private RecyclerviewClickListener listener;
public Adapter(Context context, ArrayList<User> dataList, RecyclerviewClickListener itemListener)
{
context = context;
dataList = universityArrayList;
listener = itemListener;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position)
{
holder.userName.setOnclickListener(view -> listener.recyclerviewClickListener(position));
}
}