问题
I am trying to have a fragment for CalendarView in my adroid app. If I change the date then the toast should get printed but it does not do that. I want the toast to be printed if the user changes the date. Can someone find the bug in my code? Thank you!
public class CalendarFragment extends Fragment {
public CalendarFragment() {
// Required empty public constructor
}
CalendarView cal;
Long date;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
cal = (CalendarView) v.findViewById(R.id.calendarView);
date = cal.getDate();
cal.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
if(cal.getDate() != date) {
date = cal.getDate();
Toast.makeText(view.getContext(), "Year=" + year + " Month=" + month + " Day=" + dayOfMonth, Toast.LENGTH_LONG).show();
//cal.setBackgroundColor(Color.RED);
}
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_calendar, container, false);
}
}
回答1:
You already inflated the view in onCreateView()
. But you are are doing it twice.
Change your onCreateView()
by
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
cal = (CalendarView) v.findViewById(R.id.calendarView);
date = cal.getDate();
cal.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
if(cal.getDate() != date) {
date = cal.getDate();
Toast.makeText(view.getContext(), "Year=" + year + " Month=" + month + " Day=" + dayOfMonth, Toast.LENGTH_LONG).show();
//cal.setBackgroundColor(Color.RED);
}
}
});
// Inflate the layout for this fragment
return v;
}
Hope it helps !!
来源:https://stackoverflow.com/questions/36168720/setondatechangelistener-for-calendarview-does-not-work