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

拈花ヽ惹草 提交于 2019-12-11 19:35:18

问题


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



    }

回答1:


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 )



来源:https://stackoverflow.com/questions/57313673/cant-resolve-the-context-or-application-while-navigating-from-adapter-of-a-frag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!