gpt4 book ai didi

java - LinearLayoutManager 不能在 Fragment 中使用

转载 作者:行者123 更新时间:2023-11-29 04:12:50 25 4
gpt4 key购买 nike

我的 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);

希望你能帮助我,谢谢。

最佳答案

您不能将 Fragment 转换为 Context

编辑这一行:

RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);

到:

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());

请记住在使用前为 getContext()getActivity() 检查 null。

对于下面评论中的新问题,只需将 return 语句置于函数末尾即可:

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

关于java - LinearLayoutManager 不能在 Fragment 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54003985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com