【发布时间】:2016-08-16 10:06:04
【问题描述】:
我有一个包含自定义布局和事件侦听器的片段来处理用户与自定义视图的交互。但是在片段内设置事件侦听器时出现空指针异常。在这里,我发现自定义视图引用在fragment中为null。
public class CustomCalendarView extends LinearLayout {
private EventListener eventListener;
public CustomCalendarView(Context context, AttributeSet attrs)
{
super(context);
............
cellView = (GridView) findViewById(R.id.calendar_grid);
cellView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (eventListener == null)
return false;
eventListener.onDayLongPress((Date) adapterView.getItemAtPosition(i));
return true;
}
});
}
public void setEventListener(EventListener eventListener) {
this.eventListener = eventListener;
}
public interface EventListener {
void onDayLongPress(Date date);
}
}
public class DescribeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_explore_planner, container, false);
MainActivity activity = (MainActivity) getActivity();
customCalendarView = ((CustomCalendarView) view.findViewById(R.id.calendar_view));
customCalendarView.setEventListener(new CustomCalendarView.EventListener() {
@Override
public void onDayLongPress(Date date) {
Toast.makeText(getContext(), timeFormatter.format(date), Toast.LENGTH_SHORT).show();
}
});
}
【问题讨论】:
-
请提供您的代码。设置监听器并从布局中获取视图的代码
-
你得到 NPE 是因为你的一个表达式在某处有一个空引用。可以肯定的是,大多数人都不看你的代码就能知道!
-
也许 cellView 有一个空引用?
标签: android android-fragments android-custom-view