Bra*_*tma 4 java android-studio
我有一个错误LinearLayoutManager
,当我运行这段代码时,它说
error: incompatible types: NotificationFragment cannot be converted to Context
Run Code Online (Sandbox Code Playgroud)
这是我的代码 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
错误在
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
Run Code Online (Sandbox Code Playgroud)
希望你能帮助我,谢谢。
你不能将 a 转换Fragment
为 a Context
。
编辑这一行:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
Run Code Online (Sandbox Code Playgroud)
到:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
Run Code Online (Sandbox Code Playgroud)
或者
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
Run Code Online (Sandbox Code Playgroud)
请记住在使用它之前getContext()
或getActivity()
之前检查它。
对于下面评论中的新问题,只需将 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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5696 次 |
最近记录: |