How to open a new fragment when click on the CardView + RecyclerView - android

In my app I have 15 cardview's ,Now I want to show a fragment when I clicked the cardview's for that I have 15 fragments.
RecyclerViewAdapter.java
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (getAdapterPosition()) {
case 0 :
// "What Should I do here"
}
}
});
}
}
}
Reminders.java
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
}
});
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Image
here in switch case I want to open new fragments based on the adapter's position.
Is it possible please guide me to solve ,Or if I am in wrong path please guide me ...

make interface in recycler view adapter like below code..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
String data=mStringList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
Your Code ..
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
onItemClickListner onItemClickListner;
public void setOnItemClickListner(onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(reminder str);//pass your object types.
}
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
reminder data=mData.get(position);
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
}
}
}
then after define adapter value and bind into recycler view call below code.. in activity when bind adapter into recycler view.
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
// here call your fragment
}
});
your code for fragment..
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
// here str is click item value in recyclerview.
// here perform your operation . str is give object reminder pojo class of selected item on recyclerview.
// below code you can make condition and check any value.
if(str.getItemName().equals("xyz")){
Fragment fragment = new MainFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
else if(str.getItemName().equals("ayx")){
Fragment fragment = new HomeFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
recyclerviewAdapter.notifyDataSetChanged();
}
});
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}

Try like this:
public class NewAdapter extends RecyclerView.Adapter<NewAdapter.MyViewHolder> {
Context context;
LayoutInflater inflater;
Activity activity;
View view;
RecyclerView recyclerViewNew;
private ArrayList<reminder> mData;
public NewAdapter(RecyclerView recyclerView, Context context, ArrayList<reminder>
mData, Activity activity) {
this.context = context;
this.mData = mData;
this.activity = activity;
inflater = LayoutInflater.from(this.context);
this.recyclerViewNew = recyclerView;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_cases_fragment, parent, false);
MyViewHolder sectionViewHolder = new MyViewHolder(view);
return sectionViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final int pos = position;
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = view.getContext();
Intent intent = new Intent();
switch (pos) {
case 0:
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
break;
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
cardView = (CardView) itemView.findViewById(R.id.cardView);
}
}
}
Hope this helps you.

Related

(android) How to dynamically add items to the current nested RecyclerView

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);
}
}

Onclick listner not triggering in fragment page adapter

I'm trying to display all contacts from phone to recyclerView when a user presses any item it should do some work. I have a list of contacts in a fragment which is inside a fragment page adapter when ever I click in the recyclerView item onClicklistener is not executing
I have used same code in a previous app but onclicklisteners are triggering
public class ListOfContacts extends Fragment implements OnContactListener {
private static final String TAG = "ListOfContacts";
ArrayList<ContactModel> arrayList = new ArrayList<>();
RecyclerView mRecyclerview;
ListOfContactsRAdapter listOfContactsRAdapter;
Cursor cursor;
public static ListOfContacts getInstance(ArrayList<ContactModel> arrayList) {
ListOfContacts listOfContacts = new ListOfContacts();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("listofcontacts", arrayList);
listOfContacts.setArguments(bundle);
return listOfContacts;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_of_contacts, container, false);
mRecyclerview = view.findViewById(R.id.loc_r_view);
listOfContactsRAdapter = new ListOfContactsRAdapter(getActivity(), this, arrayList);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerview.setAdapter(listOfContactsRAdapter);
mRecyclerview.addItemDecoration(new DividerItemDecoration(mRecyclerview.getContext(), DividerItemDecoration.VERTICAL));
mRecyclerview.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
arrayList.addAll(Objects.requireNonNull(getArguments().<ContactModel>getParcelableArrayList("listofcontacts")));
Log.d(TAG, "contact recived " + arrayList.get(0).getContactName());
} else {
if (getArguments().getStringArrayList("listofcontacts") != null)
arrayList.addAll(getArguments().<ContactModel>getParcelableArrayList("listofcontacts"));
}
}
}
#Override
public void onDueListener(int position) {
Log.d(TAG, "onDueListener: ");
ContactModel contactModel = new ContactModel();
contactModel.setContactName(arrayList.get(position).getContactName());
contactModel.setContactNumberp(arrayList.get(position).getContactNumberp());
contactModel.setState(true);
Intent intent = new Intent(getActivity(), AddDue.class);
intent.putExtra("userDetails", contactModel);
startActivity(intent);
}
}
public ListOfContactsRAdapter(Context context, OnContactListener a, ArrayList<ContactModel> arrayList) {
Log.d(TAG, "ListOfContactsRAdapter: +" + arrayList.size());
ContactListener = a;
this.arrayList = new ArrayList<>();
if (arrayList != null)
this.arrayList.addAll(arrayList);
mContext = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.loc_r_container, viewGroup, false);
customViewHolder = new CustomViewHolder(view, ContactListener);
return customViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder customViewHolder, int i) {
customViewHolder.contactName.setText(arrayList.get(i).getContactName());
customViewHolder.contactNumber.setText(arrayList.get(i).getContactNumberp());
customViewHolder.contactDp.setText(String.valueOf(arrayList.get(i).getContactName().charAt(0)));
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: ");
return arrayList.size();
}
static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnContactListener Listener;
TextView contactName;
TextView contactNumber;
TextView contactDp;
Button button;
LinearLayout linearLayout;
CustomViewHolder(#NonNull View itemView, OnContactListener mOnContactListener) {
super(itemView);
contactName = itemView.findViewById(R.id.contact_name);
contactNumber = itemView.findViewById(R.id.contact_number);
button = itemView.findViewById(R.id.action);
contactDp = itemView.findViewById(R.id.contactDp);
linearLayout = itemView.findViewById(R.id.container);
linearLayout.setOnClickListener(this);
Listener = mOnContactListener;
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
Listener.onDueListener(getAdapterPosition());
}
}
}
What i did is create an Interface in your RecyclerView Adapter:
public interface OnClickItem { // create an interface
void onClickItem(int position); // create callback function
}
Then in OnBindViewHolder:
customViewHolder.(yourView).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContactListener.onClickItem(customViewHolder.getAdapterPosition());
}
});
In your Fragment:
public class ListOfContacts extends Fragment implements ListOfContactsRAdapter.OnClickItem { ...
Implement the method:
#Override
public void onClickItem(int position) {
...
}

How to create an interface between a fragment and an adapter

I have been able to create an interface in the adapter to communicate with the fragment.
This is the adapter code
public class AgroInfoAdapter extends RecyclerView.Adapter<AgroInfoAdapter.ViewHolder> {
private Context mContext;
ArrayList<JsonObject> extensionItem = new ArrayList<>();
public Typeface tf;
public AgroInfoAdapter.AgroInfoAdapterListener listener;
public AgroInfoAdapter(Context context, ArrayList<JsonObject> extensionItem) {
this.extensionItem = extensionItem;
this.mContext = context;
this.tf = Typeface.createFromAsset(context.getAssets(), "FiraSans-Light.ttf");
}
#Override
public AgroInfoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_crop_info, null);
AgroInfoAdapter.ViewHolder viewHolder = new AgroInfoAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.header)
public TextView header;
#BindView(R.id.body)
public TextView body;
#BindView(R.id.thumbnail)
public ImageView thumbnail;
#BindView(R.id.button)
public Button button;
#BindView(R.id.downloadProgressView)
DownloadProgressView downloadProgressView;
#BindView(R.id.row)
public LinearLayout row;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
ButterKnife.bind(this, itemLayoutView);
}
}
#Override
public void onBindViewHolder(AgroInfoAdapter.ViewHolder viewHolder, final int position) {
try {
JsonObject sl = extensionItem.get(position);
viewHolder.header.setText(sl.get("title").getAsString());
if ((sl.get("title").getAsString()).equals("Land preparation")) {
viewHolder.button.setVisibility(View.VISIBLE);
}
Glide.with(mContext).load(CONFIG.IMAGE_URL+ sl.get("photo_url").getAsString())
.thumbnail(0.5f)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fallback(R.drawable.fallback)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.fallback)
)
.into(viewHolder.thumbnail);
String description="";
for (JsonElement e:sl.get("description").getAsJsonArray()){
if(!e.getAsString().trim().isEmpty() && CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf(e.getAsString().trim())) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";
}else if(!e.getAsString().trim().isEmpty()) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";;
viewHolder.body.setText(description);
viewHolder.body.setTypeface(tf);
}
}
} catch (Exception e) {
}
applyClickEvents(viewHolder, position);
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onCartRowClicked(view, holder.downloadProgressView, position);
}
});
}
#Override
public int getItemCount() {
return extensionItem.size();
}
}
This is the frgament which I was connecting to the adapter
AgroInfoAdapter adapter;
#BindView(R.id.rv)
RelativeLayout _RecyclerViewLayout;
#BindView(R.id.empty_rv)
RelativeLayout _EmptyRecyclerViewLayout;
#BindView(R.id.recycler_desc)
RecyclerView recyclerView;
Toolbar mToolbar;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
#BindView(R.id.rv_layout) RelativeLayout relativeLayout;
ArrayList<JsonObject> ins = new ArrayList<>();
AgroInfoActivity.OnCropperSpinnerSelectedListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new AgroInfoActivity.OnCropperSpinnerSelectedListener() {
#Override
public void onItemSelected(String pos) {
new LongOperation().execute(pos);
}
};
((AgroInfoActivity)getActivity()).addCropperSpinnerSelectedListener(listener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ext_land, container, false);
ButterKnife.bind(this,view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new AgroInfoAdapter(getActivity(), ins);
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onResume() {
new LongOperation().execute(((AgroInfoActivity)getActivity()).cropsSpinner.getSelectedItem().toString());
super.onResume();
}
private class LongOperation extends AsyncTask<String, Void, ArrayList<JsonObject>> {
#Override
protected ArrayList<JsonObject> doInBackground(String... params) {
try {
couchdbCropInfo = new CouchdbCropInfo(getActivity());
return couchdbCropInfo.allCropInfo(params[0],TYPE);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JsonObject> result) {
ins.addAll(result);
adapter.notifyDataSetChanged();
if (ins.isEmpty()) {
_RecyclerViewLayout.setVisibility(View.GONE);
_EmptyRecyclerViewLayout.setVisibility(View.VISIBLE);
} else {
_RecyclerViewLayout.setVisibility(View.VISIBLE);
_EmptyRecyclerViewLayout.setVisibility(View.GONE);
}
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
protected void onPreExecute() {
relativeLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
ins.clear();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getActivity()
.getFragmentManager()
.beginTransaction();
Fragment fragmentB = new PostFragment();
fragmentB.setArguments(bundle);
fragmentTransaction.replace(R.id.parent, fragmentB);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Basically what I am trying to achieve is I want to call a fragment when I click the button. The activity is a tablaout with about 5 fragments.
When I click the button. What brings about this and how best can I solve it or could have done it? Thanks in advance.
In place where you declare adapter or in the constructor of adapter, initiate the listener.
In the fragment side,
class Test extends Fragment {
AdapterClass adapter = new AdapterClass();
adapter.setListner(..)
view.setAdapter(adapter);
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
}
}
In Adapter class
class AdapterClass {
private AgroInfoAdapterListener listner;
public setListner(AgroInfoAdapterListener listner) {
this.listner = listner;
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}

Calling setAdapter on Fragment (Recycler View) not working

I tried to set the adapter on fragment, but nothing shows up.
The object retrieves the data from API but doesn't show on the screen.
I have already put the break point on rvItem.setAdapter(mainAdapter); but nothings happen, the debug passes straight through.
public class ItemFragment extends Fragment {
private MainAdapter mainAdapter;
private ItemPresenter itemPresenter;
private GridLayoutManager mLayoutManager;
private List<ObjectAdapter> list = new ArrayList<>();
private String region = "br";
#Bind(R.id.rvItem)
RecyclerView rvItem;
public ItemFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_item, container, false);
ButterKnife.bind(this, view);
itemPresenter = new ItemPresenter();
mLayoutManager = new GridLayoutManager(getActivity(), 4);
rvItem.setLayoutManager(mLayoutManager);
getList();
return view;
}
private void getList() {
itemPresenter.loadItemList(region, "all", AppConfigs.api_key, new ItemListListener() {
#Override
public void onRequestStarted() {
}
#Override
public void onRequestFinished() {
}
#Override
public void onError(Throwable error) {
}
#Override
public void onItemListLoad(List<ItemDto> itemList) {
displayItemList(ObjectAdapter.convertItemToObjetct(itemList));
}
});
}
public void displayItemList(List<ObjectAdapter> itemList) {
list = itemList;
mainAdapter = new MainAdapter(getActivity(), list, new MainAdapter.OnObjectClickListener() {
#Override
public void OnObjectClickListener(ObjectAdapter objectAdapter) {
Toast.makeText(getActivity(), "Object Adapter" + objectAdapter.Id, Toast.LENGTH_SHORT).show();
}
});
rvItem.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
}
}
Adapter:
public class MainAdapter extends
RecyclerView.Adapter<MainAdapter.MainAdapterViewHolder> {
public List<ObjectAdapter> mObjecterList;
private final OnObjectClickListener listener;
private Context mContext;
public interface OnObjectClickListener {
void OnObjectClickListener(ObjectAdapter objectAdapter);
}
public MainAdapter(Context context, List<ObjectAdapter> objectAdapterList, OnObjectClickListener listener) {
this.mObjecterList = objectAdapterList;
this.listener = listener;
this.mContext = context;
}
#Override
public MainAdapter.MainAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_adapter, parent, false);
return new MainAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.MainAdapterViewHolder holder, int position) {
ObjectAdapter ob = mObjecterList.get(position);
holder.tvNameText.setText(ob.Name);
holder.bind(mObjecterList.get(position), listener);
String url = "";
switch (ob.Type){
case CHAMPION: url = String.format(AppConfigs.portraitChampion, ob.Portrait);
break;
case SPELL: url = String.format(AppConfigs.portraitSpell, ob.Portrait);
break;
case ITEM: url = String.format(AppConfigs.portraitItem, ob.Portrait);
break;
}
Picasso.with(mContext).load(url).into(holder.ivRetrato);
}
#Override
public int getItemCount() {
return this.mObjecterList.size();
}
public static class MainAdapterViewHolder extends RecyclerView.ViewHolder {
public TextView tvNameText;
public ImageView ivRetrato;
public MainAdapterViewHolder(View itemView) {
super(itemView);
this.tvNameText = (TextView) itemView.findViewById(R.id.tvNameText);
this.ivRetrato = (ImageView) itemView.findViewById(R.id.ivImagePortrait);
}
public void bind(final ObjectAdapter objectAdapterListItem, final OnObjectClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.OnObjectClickListener(objectAdapterListItem);
}
});
}
}
}
You need to set adapter directly at onCreateView method and call notifyDataSetChanged() of adapter when data loaded

Handle button click inside row in recyclerView

I would like to know how to handle position of the row if the adapter is changed - for example if I write something to SearchView - adapter has changed and position is different. I have done this (below), but it shows the item before changed position.
My issue is with Recycler view item click.
Could you help me with that?
Adapter
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private static OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
private List<Contact> mContacts;
private List<Contact> mContactsFiltered;
SearchViewFilter filter;
Context mContext;
public ContactsRecyclerAdapter(Context context, List<Contact> contact) {
this.mContext = context;
this.mContacts = contact;
this.mContactsFiltered = contact;
filter = new SearchViewFilter(mContacts, this);
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
public ViewDataBinding getBinding() {
return binding;
}
}
#Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
#Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContactsFiltered.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
Fragment
public class ContactListFragment extends Fragment implements View.OnClickListener {
FloatingActionButton fabButton;
SearchView searchView;
RecyclerView recyclerView;
String name, number, email;
private List<Contact> mContact = new ArrayList<>();
private ContactsRecyclerAdapter mAdapter;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
searchView = (SearchView) view.findViewById(R.id.search_view);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mContact = SugarRecord.listAll(Contact.class);
mAdapter = new ContactsRecyclerAdapter(getActivity(), mContact);
recyclerView.setAdapter(mAdapter);
//item click
mAdapter.setOnItemClickListener(new ContactsRecyclerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
Contact contact = SugarRecord.findById(Contact.class, (long) position + 1);
name = contact.getName();
number = contact.getNumber();
email = contact.getEmail();
showAlertDialog();
}
});
searchFilter();
return view;
}
public void sortList() {
if(mContact.size() > 0) {
if (!isSort) {
Collections.sort(mContact, new Comparator<Contact>() {
#Override
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
});
}
else {
Collections.reverse(mContact);
isSort = false;
}
}
mAdapter.notifyDataSetChanged();
Click listener does not work with a RecyclerView. use OnItemTouchListener()
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
you have to overide onclick in BindingHolder class. Inside onclick method invoke a callback method of object passed via constructor etc
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
public void onClick(View view) {
//call a callback method here
}
}
public ViewDataBinding getBinding() {
return binding;
}
}

Categories

Resources