LinearLayoutManager不能在Fragment

时间:2019-01-02 09:33:53

标签: java android-studio

运行此代码时,我的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);

希望您能帮助我,谢谢。

2 个答案:

答案 0 :(得分:1)

您不能将Fragment投射到Context

编辑此行:

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

收件人:

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

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

请记住在使用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;
}

答案 1 :(得分:1)

使用getActivity()代替NotificationFragment。this

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