[英]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. 我试图从一个片段(A)导航到另一个(B),但是该片段但第一个片段(A)具有recyclerView的含义,当我单击任何项目时,我应该导航至下一个。 Am using android Navigation component but I couldn't resolve the method findNavController(xxx)
since it requires the ApplicationContext of the fragment. 我正在使用android导航组件,但是我无法解析方法findNavController(xxx)
因为它需要该片段的ApplicationContext。 , because I tried v.getContext()
, v.getApplicationContext()
, mContext
, but there wasn't luck. ,因为我尝试了v.getContext()
, v.getApplicationContext()
, mContext
,但是没有运气。
How can I resolve this issue, below is the onBindViewHolder()
in the RecyclerView Adapter class. 如何解决此问题,以下是RecyclerView Adapter类中的onBindViewHolder()
。 ? ?
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. RecyclerView的适配器不负责重定向到另一个片段。
Create interface like 创建类似的界面
public interface OnItemClickListener {
void onItemClicked(int position)
}
Inside your RecyclerView's adapter add method: 在您的RecyclerView的适配器添加方法内:
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 ) 希望对你有帮助)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.