简体   繁体   中英

Can't resolve the Context or Application while navigating from Adapter of a fragment(A) to another Fragment (B)

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



    }

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM