我正在尝试在DialogFragment内部填充RecyclerView,这是在片段内部。 我按照指南正常制作了RecyclerView适配器。
但我收到此错误java.lang.NullPointerException: Attempt to invoke virtual method 'voidandroid.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
在线
recyclerView.setLayoutManager(经理);
这里是完整的代码
public class AlertFragment extends DialogFragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter2;
RecyclerView.LayoutManager manager;
ArrayList<String> goalname = new ArrayList<String>();
ArrayList<String> goalcategory = new ArrayList<String>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_alert, container, false);
goalname.add("Running");
goalcategory.add("Physical");
goalname.add("Yoga");
goalcategory.add("Physical");
goalname.add("Gym");
goalcategory.add("Physical");
goalname.add("Meditation");
goalcategory.add("Mental");
goalname.add("Puzzle Solving");
goalcategory.add("Habits");
manager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
recyclerView.setLayoutManager(manager);
adapter2 = new GoalListAdapter(goalname, goalcategory,getActivity());
recyclerView.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
return v;
}}
答案 0 :(得分:1)
显然它会崩溃,因为它没有找到回收站视图实例。
只需替换此行:
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
。通过强>
recyclerView = (RecyclerView) v.findViewById(R.id.bookhistory);
现在它适合你。
答案 1 :(得分:0)
你的问题在于这一行:
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
您真的希望从您在此行中的片段中充气的视图中获取RecyclerView
View v = inflater.inflate(R.layout.fragment_alert, container, false);
所以要解决这个问题,请将我提到的第一行代码更改为
recyclerView = (RecyclerView) v.findViewById(R.id.bookhistory);
这假设DialogFragment包含bookhistory