我的LinearLayoutManager上有一个错误,当我运行这段代码时,它说
error: incompatible types: NotificationFragment cannot be converted to Context下面是我的代码NotificationFragment.java
public class NotificationFragment extends Fragment {
private RecyclerView recyclerView;
private NotificationAdapter adapter;
private ArrayList<NotificationModel> notificationModelArrayList;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_notification,container,false);
addData();
recyclerView = (RecyclerView) getView().findViewById(R.id.recycler_view);
adapter = new NotificationAdapter(notificationModelArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
void addData(){
notificationModelArrayList = new ArrayList<>();
notificationModelArrayList.add(new NotificationModel("Event 1", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 2", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 3", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 4", "1 January 2019", "Surabaya"));
}
}错误亮起
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);希望你能帮助我,谢谢。
发布于 2019-01-02 17:46:57
不能将Fragment转换为Context。
编辑此行:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);至:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());或
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());记住在使用之前检查getContext()或getActivity()是否为null。
对于下面评论中的新问题,只需将返回语句放在函数的末尾:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notification,container,false);
addData();
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
adapter = new NotificationAdapter(notificationModelArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
return view;
}发布于 2019-01-02 17:47:11
使用getActivity()而不是NotificationFragment.this
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());https://stackoverflow.com/questions/54003985
复制相似问题