Answer the question
In order to leave comments, you need to log in
How to open fragment on click of recycler view element?
I have a fragment in my activity with a recycler view (vertical list). How can I make it so that on clicking any element in this list, another fragment opens?
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.ViewHolder> {
private MessagesFragment mContext;
private ArrayList<MessagesObject> MessagesArrayList;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name, description, timestamp, count;
public ImageView avator;
public ViewHolder(View view) {
super(view);
avator = (ImageView)itemView.findViewById(R.id.item_chat_avatar);
name = (TextView) itemView.findViewById(R.id.dialog_title);
description = (TextView) itemView.findViewById(R.id.dialog_message);
timestamp = (TextView) itemView.findViewById(R.id.item_chat_date);
count = (TextView) itemView.findViewById(R.id.item_chat_unread_count);
}
}
public MessagesAdapter(MessagesFragment mContext, ArrayList<MessagesObject> MessagesArrayList) {
this.mContext = mContext;
this.MessagesArrayList = MessagesArrayList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_messege, parent, false);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
MessagesObject songs = MessagesArrayList.get(position);
Glide.with(mContext).load(R.drawable.a_avator).into(holder.avator);
holder.name.setText(songs.getMessagesName());
holder.description.setText(songs.getMessagesDescription());
holder.timestamp.setText(songs.getMessagesTime());
holder.count.setText(songs.getMessagesUnread());
}
@Override
public int getItemCount() {
return MessagesArrayList.size();
}
}
Answer the question
In order to leave comments, you need to log in
There are several options:
1. A good way. You need to pass some listener to the RecyclerView constructor, the method of which will be called by clicking on an element in the list.
2. Bad way. It can be assumed that the context of the view in the RecyclerView is some specific activity. Let it be MainActivity for example. Then we can cast the View v context from OnClickListener to the MainActivity type and call the public MainActivity method there, which will do something with the fragments. Well, either directly take the FragmentManager from the Activity and do something.
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Вот здесь ((MainAcivity)(v.getContext())).yourFunction
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question