我在setFill
startActivity
内的onClickListener
内调用RecyclerView
后,在logcat中收到以下错误。
Fragment
在创建其他活动(java.lang.NullPointerException
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1764)
at android.view.View.measure(View.java:15293)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:861)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:602)
at android.view.View.measure(View.java:15293)
已调用)
以下是OnCreate
的{{1}}:
Fragment
onViewCreated
的代码:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
RecyclerView list = (RecyclerView) view.findViewById(R.id.list);
list.setHasFixedSize(true);
list.addItemDecoration(new DividerItemDecoration(getResources()));
//Tried commenting out three of the following lines, no effect
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
list.setLayoutManager(layoutManager);
list.setItemAnimator(new DefaultItemAnimator());
ArrayList<TimelineItem> timelineItems = new ArrayList<>();
//populating the list with dummy data
adapter = new TimelineAdapter(timelineItems);
//this sets the onclick listener on the view inside the ViewHolder
adapter.setPrimaryClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openProfile();
}
});
list.setAdapter(adapter);
适配器代码:
openProfile
事实证明,切换到新活动时总会发生此错误。不是特定于此public void openProfile(){
Intent intent = new Intent(getActivity(), ProfileActivity.class);
//NPE happens after this
getActivity().startActivity(intent);
}
答案 0 :(得分:0)
可能该片段尚未附加到活动,因此getActivity()返回null。处理片段时,可以覆盖onAttach()
并从那里获取活动的实例,以确保片段已附加。
答案 1 :(得分:0)
onBindViewHolder(VH持有者,int位置)
由RecyclerView调用以在指定位置显示数据。此方法应更新itemView的内容以反映给定位置的项目。 块引用
也许你错过了super.onBindViewHolder(viewHolder, i)
?
答案 2 :(得分:0)
想出来,结果我使用的是v7-recyclerview
的第21版,将其更新为22解决了这个