I have converted a RecyclerView from Activity to Fragment all work but when i click on item i have this error:
java.lang.NullPointerException: Attempt to invoke interface method 'void fragment.MyRecyclerViewAdapter$MyClickListener.onItemClick(int, android.view.View)' on a null object reference
This error is in myClickListener.onItemClick(getAdapterPosition(), v);
public class MyRecyclerViewAdapter extends RecyclerView
.Adapter<MyRecyclerViewAdapter
.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
TextView dateTime;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v); //ERROR HERE
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This code is in fragment:
mView = inflater.inflate(R.layout.fragment_two, container, false);
mRecyclerView = (RecyclerView) mView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
return mView;
You are not calling
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
from anywhere.
Call this method from your adapter or fragment. Or if you do not want right now, just add null check
#Override
public void onClick(View v) {
if (myClickListener!= null) {
myClickListener.onItemClick(getAdapterPosition(), v); //ERROR HERE
}
}
And add below code into Fragment class.
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
// Implement your logic to do after clicking on any item.
}
});
Before calling the set adapter on your recyclerview call setOnItemClickListener
I have solved with:
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.wtf("TEST", position);
}
});
Related
I am using diffutil for my recycler adapters and I need many recyclerview for categorization. Should I create adapter for every recyclerview? Same view, same type data, same functions, different data btw
If you check your recycler view's onBindViewHolder method it has your holder parameter which provides you with the instance of different ViewHolders you have and accordingly set the layout for the recycler view.
For example, in my case I had to use a single recyclerView adapter to create an instance Income as well as expense in a list.
This is how my onBindViewHolder looks:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
DialogDetails d=new DialogDetails();
if (holder instanceof IncomeListHolder){
((IncomeListHolder)holder).categoryText.setText(expensesList.get(position).getCategory());
((IncomeListHolder)holder).incomeText.setText("+"+expensesList.get(position).getAmount());
((IncomeListHolder)holder).incomeText.setTextColor(context.getResources().getColor(R.color.income_color));
}
if (holder instanceof ExpensesListHolder){
((ExpensesListHolder) holder).category.setText(list.get(position-expensesList.size()).getCategory());
((ExpensesListHolder) holder).expenseText.setText("-"+list.get(position- expensesList.size()).getExpense());
((ExpensesListHolder) holder).expenseText.setTextColor(context.getResources().getColor(R.color.expense_color));
}
//.setText(String.valueOf(balanceList.get(position).getIncome()));
}
You also have to create separate viewHolders for all the list data you wish to display,like:
public class IncomeListHolder extends RecyclerView.ViewHolder {
TextView categoryText;
TextView incomeText;
public IncomeListHolder(#NonNull View itemView) {
super(itemView);
categoryText=itemView.findViewById(R.id.main_category_text_view);
incomeText=itemView.findViewById(R.id.expenses_text_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getIncomeData(expensesList.get(position),view);
details.setUpdate(true);
}
}
});
}
}
public class ExpensesListHolder extends RecyclerView.ViewHolder{
TextView category;
TextView expenseText;
public ExpensesListHolder(#NonNull View itemView) {
super(itemView);
category=itemView.findViewById(R.id.main_category_text_view_2);
expenseText=itemView.findViewById(R.id.expenses_text_view_2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getExpenseData(list.get(position-expensesList.size()),view);
details.setUpdate(true);
}
}
});
}
}
My whole recycler view adapter:
public class IncomeListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
final int VIEW_TYPE_INCOME=0;
final int VIEW_TYPE_EXPENSE=1;
View view;
List<DataBaseEntity> expensesList=new ArrayList<>();
List<ExpenseDataEntity> list=new ArrayList<>();
Context context;
OnItemClickListener listener;
DialogDetails details=new DialogDetails();
public IncomeListAdapter(Context context) {
this.context = context;
}
//
// View v=LayoutInflater.from(context).inflate(R.layout.fragment_expense_home,null);
//// t=v.findViewById(R.id.income_text_view);
// }
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType==VIEW_TYPE_INCOME) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.expenses_list, parent, false);
return new IncomeListHolder(view);
}
if (viewType==VIEW_TYPE_EXPENSE){
view=LayoutInflater.from(parent.getContext()).inflate(R.layout.expense_layout_list,parent,false);
return new ExpensesListHolder(view);
}
return null;
}
public interface OnItemClickListener{
void getIncomeData(DataBaseEntity dataBaseEntity,View view);
void getExpenseData(ExpenseDataEntity expenseDataEntity,View view);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener=listener;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
DialogDetails d=new DialogDetails();
if (holder instanceof IncomeListHolder){
((IncomeListHolder)holder).categoryText.setText(expensesList.get(position).getCategory());
((IncomeListHolder)holder).incomeText.setText("+"+expensesList.get(position).getAmount());
((IncomeListHolder)holder).incomeText.setTextColor(context.getResources().getColor(R.color.income_color));
}
if (holder instanceof ExpensesListHolder){
((ExpensesListHolder) holder).category.setText(list.get(position-expensesList.size()).getCategory());
((ExpensesListHolder) holder).expenseText.setText("-"+list.get(position- expensesList.size()).getExpense());
((ExpensesListHolder) holder).expenseText.setTextColor(context.getResources().getColor(R.color.expense_color));
}
//.setText(String.valueOf(balanceList.get(position).getIncome()));
}
public DataBaseEntity getDataAt(int position){
return expensesList.get(position);
}
public ExpenseDataEntity getExpenseAt(int position){
return list.get(position- expensesList.size());
}
#Override
public int getItemCount() {
return expensesList.size()+list.size();
}
#Override
public int getItemViewType(int position) {
if (position< expensesList.size()){
return VIEW_TYPE_INCOME;
}
if (position-expensesList.size()< list.size()){
return VIEW_TYPE_EXPENSE;
}
return -1;
}
public void setExpensesList(List<DataBaseEntity> expensesList){
this.expensesList=expensesList;
notifyDataSetChanged();
}
public void setList(List<ExpenseDataEntity> list){
this.list=list;
notifyDataSetChanged();
}
// public void setBalanceList(List<BalanceSheetEntity> balanceList){
// this.balanceList=balanceList;
// notifyDataSetChanged();
// }
public class IncomeListHolder extends RecyclerView.ViewHolder {
TextView categoryText;
TextView incomeText;
public IncomeListHolder(#NonNull View itemView) {
super(itemView);
categoryText=itemView.findViewById(R.id.main_category_text_view);
incomeText=itemView.findViewById(R.id.expenses_text_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getIncomeData(expensesList.get(position),view);
details.setUpdate(true);
}
}
});
}
}
public class ExpensesListHolder extends RecyclerView.ViewHolder{
TextView category;
TextView expenseText;
public ExpensesListHolder(#NonNull View itemView) {
super(itemView);
category=itemView.findViewById(R.id.main_category_text_view_2);
expenseText=itemView.findViewById(R.id.expenses_text_view_2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getExpenseData(list.get(position-expensesList.size()),view);
details.setUpdate(true);
}
}
});
}
}
}
This picture shows the problem.
I am using nested RecyclerView right now.
What I want is that when the ADD button of the outer RecyclerView is pressed, the item of the inner RecyclerView is added.
But what I made is that no matter which button is pressed, the last added inner RecyclerView's item is added.
How can I add items each the proper RecyclerView position?
This is my code.
RoutineModel.java
public class RoutineModel {
String routine;
public RoutineModel(String routine) {
this.routine = routine;
}
public String getRoutine() {
return routine;
}
}
RoutineAdapter.java
public class RoutineAdapter extends RecyclerView.Adapter<RoutineAdapter.ViewHolder> {
Context context;
ArrayList<RoutineModel> routineItems = new ArrayList<>();
public RoutineDetailAdapter detailAdapter;
OnRoutineItemClickListener listener;
public void setOnRoutineClickListener(OnRoutineItemClickListener listener) {
this.listener = listener;
}
public void addItem(RoutineModel item) {
routineItems.add(item);
}
public void addDetailItem() {
detailAdapter.addItem(new RoutineDetailModel());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.routine_item, parent, false);
ViewHolder holder = new ViewHolder(itemView);
detailAdapter = new RoutineDetailAdapter();
holder.setRoutineDetailRecyClerView();
holder.routine_detail.setAdapter(detailAdapter);
detailAdapter.addItem(new RoutineDetailModel());
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
RoutineModel curRoutineItem = routineItems.get(position);
holder.setItems(curRoutineItem);
}
#Override
public int getItemCount() {
return routineItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView routine;
Button addSet;
RecyclerView routine_detail;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initViews();
addSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.OnItemClick();
}
});
}
private void initViews() {
routine = itemView.findViewById(R.id.routine);
routine_detail = itemView.findViewById(R.id.detail_routine);
addSet = itemView.findViewById(R.id.add_set);
}
private void setItems(RoutineModel routineItem) {
routine.setText(routineItem.getRoutine());
}
public void setRoutineDetailRecyClerView() {
routine_detail.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
routine_detail.setHasFixedSize(true);
}
}
public interface OnRoutineItemClickListener {
public void OnItemClick();
}
}
RoutineDetailModel
public class RoutineDetailModel {
String set;
String weight;
String reps;
}
RoutineDetailAdapter
public class RoutineDetailAdapter extends RecyclerView.Adapter<RoutineDetailAdapter.ViewHolder>{
ArrayList<RoutineDetailModel> items = new ArrayList<>();
public void addItem(RoutineDetailModel item) {
items.add(item);
notifyDataSetChanged();
}
public ArrayList<RoutineDetailModel> getItem() {
return this.items;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.routine_detail_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
RoutineDetailModel item = items.get(position);
holder.setItem(item);
}
#Override
public int getItemCount() {
return items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView set;
public ViewHolder(#NonNull View itemView) {
super(itemView);
set = itemView.findViewById(R.id.set);
}
private void setItem(RoutineDetailModel item) {
set.setText("TEST");
}
}
}
MainActivity
public class WriteRoutineActivity extends AppCompatActivity {
RecyclerView routine_recyclerview;
TextView title;
RoutineAdapter routineAdapter;
LinearLayoutManager routineLayoutManger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_routine);
initViews();
setPageTitle(getIntent());
setRoutineRecyclerview();
routineAdapter = new RoutineAdapter();
routine_recyclerview.setAdapter(routineAdapter);
// add detail item
routineAdapter.setOnRoutineClickListener(new RoutineAdapter.OnRoutineItemClickListener() {
#Override
public void OnItemClick() {
routineAdapter.addDetailItem();
}
});
}
private void initViews() {
title = findViewById(R.id.body_part_detail_title);
routine_recyclerview = findViewById(R.id.routine_recyclerview);
add_routine_btn = findViewById(R.id.add_routine);
}
private void setRoutineRecyclerview() {
routineLayoutManger = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
routine_recyclerview.setLayoutManager(routineLayoutManger);
routine_recyclerview.setHasFixedSize(true);
}
public void addRoutine(String routine) {
routineAdapter.addItem(new RoutineModel(routine));
routineLayoutManger.scrollToPositionWithOffset(0, 0);
}
}
detailAdapter in RoutineAdapter gets re-assigned every time onCreateViewHolder gets called meaning it will always point to the RoutineDetailAdapter of the last item created in the RecyclerView.
A fix for this could be to pass the RoutineDetailAdapter of the clicked item with the click listener interface.
public class RoutineAdapter extends RecyclerView.Adapter<RoutineAdapter.ViewHolder> {
Context context;
ArrayList<RoutineModel> routineItems = new ArrayList<>();
OnRoutineItemClickListener listener;
public void setOnRoutineClickListener(OnRoutineItemClickListener listener) {
this.listener = listener;
}
public void addItem(RoutineModel item) {
routineItems.add(item);
}
public void addDetailItem(RoutineDetailAdapter routineDetailAdapter) {
routineDetailAdapter.addItem(new RoutineDetailModel());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.routine_item, parent, false);
ViewHolder holder = new ViewHolder(itemView);
RoutineDetailAdapter detailAdapter = new RoutineDetailAdapter();
holder.setRoutineDetailRecyClerView();
holder.routine_detail.setAdapter(detailAdapter);
detailAdapter.addItem(new RoutineDetailModel());
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
RoutineModel curRoutineItem = routineItems.get(position);
holder.setItems(curRoutineItem);
}
#Override
public int getItemCount() {
return routineItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView routine;
Button addSet;
RecyclerView routine_detail;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initViews();
addSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RoutineDetailAdapter routineDetailAdapter = (RoutineDetailAdapter) routine_detail.getAdapter();
listener.OnItemClick(routineDetailAdapter);
}
});
}
private void initViews() {
routine = itemView.findViewById(R.id.routine);
routine_detail = itemView.findViewById(R.id.detail_routine);
addSet = itemView.findViewById(R.id.add_set);
}
private void setItems(RoutineModel routineItem) {
routine.setText(routineItem.getRoutine());
}
public void setRoutineDetailRecyClerView() {
routine_detail.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
routine_detail.setHasFixedSize(true);
}
}
public interface OnRoutineItemClickListener {
public void OnItemClick(RoutineDetailAdapter adapter);
}
}
public class WriteRoutineActivity extends AppCompatActivity {
RecyclerView routine_recyclerview;
TextView title;
RoutineAdapter routineAdapter;
LinearLayoutManager routineLayoutManger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_routine);
initViews();
setPageTitle(getIntent());
setRoutineRecyclerview();
routineAdapter = new RoutineAdapter();
routine_recyclerview.setAdapter(routineAdapter);
// add detail item
routineAdapter.setOnRoutineClickListener(new RoutineAdapter.OnRoutineItemClickListener() {
#Override
public void OnItemClick(RoutineDetailAdapter routineDetailAdapter) {
routineAdapter.addDetailItem(routineDetailAdapter);
}
});
}
private void initViews() {
title = findViewById(R.id.body_part_detail_title);
routine_recyclerview = findViewById(R.id.routine_recyclerview);
add_routine_btn = findViewById(R.id.add_routine);
}
private void setRoutineRecyclerview() {
routineLayoutManger = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
routine_recyclerview.setLayoutManager(routineLayoutManger);
routine_recyclerview.setHasFixedSize(true);
}
public void addRoutine(String routine) {
routineAdapter.addItem(new RoutineModel(routine));
routineLayoutManger.scrollToPositionWithOffset(0, 0);
}
}
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);
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);
I want to do different job for different RecycleView item. I created custom OnClickListener for RecycleView and using this from my activity. But problem is when I want to get RecycleView Item Id form OnClick it's return -1. I can't able to check view Id.
RecycleView Adapter:
public class AddFoodAdapter extends RecyclerView.Adapter<AddFoodAdapter.AddFoodApapterVH>{
private ArrayList<FoodReviewItem> foodList = new ArrayList<>();
OnItemClickListener onItemClickListener;
public AddFoodAdapter(){
}
#Override
public AddFoodApapterVH onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycleview_add_food_item, parent, false);
return new AddFoodApapterVH(itemView);
}
#Override
public void onBindViewHolder(AddFoodApapterVH holder, int position) {
holder.tvFoodTitle.setText(foodList.get(position).getFoodName());
holder.tvFoodPrice.setText(foodList.get(position).getFoodPrice());
}
public void add(int position,FoodReviewItem foodItem){
foodList.add(position,foodItem);
notifyItemInserted(position);
}
public void delete(int position){
foodList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return foodList.size();
}
public class AddFoodApapterVH extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView ivEditFoodItem;
public TextView tvFoodTitle;
public RatingBar rbFoodRating;
public ImageView ivDeleteFoodItem;
public TextView tvFoodPrice;
public AddFoodApapterVH(View itemView) {
super(itemView);
ivEditFoodItem = (ImageView) itemView.findViewById(R.id.ivEditFoodItem);
tvFoodTitle = (TextView) itemView.findViewById(R.id.tvAddFoodItemTitle);
rbFoodRating = (RatingBar) itemView.findViewById(R.id.rbAddFoodItemRating);
ivDeleteFoodItem = (ImageView) itemView.findViewById(R.id.ivDeleteFoodItem);
tvFoodPrice = (TextView) itemView.findViewById(R.id.tvAddFoodItemPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(onItemClickListener!=null){
onItemClickListener.onItemClick(v, getAdapterPosition());
}
}
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
}
Form Activity:
private void setUpFoodItemApapter() {
foodItemRecyclerView = (RecyclerView) findViewById(R.id.rvFoodItems);
addFoodAdapter = new AddFoodAdapter();
final LinearLayoutManager layoutManager = new org.solovyev.android.views.llm.LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
foodItemRecyclerView.setLayoutManager(layoutManager);
foodItemRecyclerView.addItemDecoration(new DividerItemDecoration(this, null));
foodItemRecyclerView.setAdapter(addFoodAdapter);
addFoodAdapter.SetOnItemClickListener(new AddFoodAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.i("getid",""+view.getId()); //return -1
Log.i("getid",""+R.id.ivDeleteFoodItem); //return id
// not working
if(view.getId() == R.id.ivDeleteFoodItem){
addFoodAdapter.delete(position);
}
}
});
}
addFoodAdapter.SetOnItemClickListener(new AddFoodAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
ImageView iv = (ImageView)view;// get imageView
int id = iv.getId();
if(id == R.id.ivDeleteFoodItem){
addFoodAdapter.delete(position);
}
}
});