setOnDateChangeListener for CalendarView does not work

江枫思渺然 提交于 2019-12-12 13:40:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!