CalendarView的setOnDateChangeListener不起作用

时间:2016-03-23 02:24:33

标签: java android calendarview

我正在尝试在我的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);
}

}

1 个答案:

答案 0 :(得分:1)

您已在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;
}

希望它有所帮助!!