CalendarView 的 setOnDateChangeListener 不起作用

setOnDateChangeListener for CalendarView does not work

我想在我的 adroid 应用程序中为 CalendarView 添加一个片段。如果我更改日期,则应该打印吐司,但它不会那样做。如果用户更改日期,我希望打印吐司。有人能找到我代码中的错误吗? 谢谢!

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);
}

}

您已经在 onCreateView() 中放大了视图。但是你正在做两次。 将您的 onCreateView() 更改为

 @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;
}

希望对您有所帮助!!