Issue
Am trying to navigate from one fragment (A) to another (B), but the fragment, but the first fragment (A) has a recyclerView meaning when I click on any Item I should navigate to the next one. Am using android Navigation component but I couldn't resolve the method findNavController(xxx)
since it requires the ApplicationContext of the fragment. , because I tried v.getContext()
, v.getApplicationContext()
, mContext
, but there wasn't luck.
How can I resolve this issue, below is the onBindViewHolder()
in the RecyclerView Adapter class. ?
What could be the best way to reslve this
@Override
public void onBindViewHolder(@NonNull final CoordinatesViewHolder holder, int position) {
final Coordinates coord = mCoordinates.get(position);
holder.place_name.setText(coord.getmUPlaceName());
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavHostFragment.findNavController(xxx).navigate(R.id.action_bookmarking_to_weatherFragment);
}
});
}
Solution
It is not the responsibility of RecyclerView's adapter to redirect to another fragment.
Create interface like
public interface OnItemClickListener {
void onItemClicked(int position)
}
Inside your RecyclerView's adapter add method:
public class YourAdapterName extend RecyclerView.Adapter...
private OnItemClickListener onItemClickListener
void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener
}
...
@Override
public void onBindViewHolder(@NonNull final CoordinatesViewHolder holder, int position) {
final Coordinates coord = mCoordinates.get(position);
holder.place_name.setText(coord.getmUPlaceName());
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(onItemClickListener != null) {
onItemClickListener.onItemClicked(position)
}
}
});
}
In your fragment with recycler, in place where you set adapter add code:
YourAdapterClassName adapter = new YourAdapterClassName(...init adapter...)
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClicked(int position) {
//Navigate here
}
})
yourRecyclerName.setAdapter(adapter)
Hope it'll help )
Answered By - Peter Staranchuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.