我想在一个Fragment中使用CalendarView,但是我找不到如何通过Java访问它的方法。首先,我只是想在烤面包中显示选定的日期,但是如果我单击一个日期,该函数似乎没有被调用。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.SchedulerFragment">
    <CalendarView
        android:id="@+id/scheduler_calendar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></CalendarView>
</RelativeLayout>


public class SchedulerActivity extends AppCompatActivity {
    private CalendarView calendarView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        calendarView = (CalendarView) findViewById(R.id.scheduler_calendar);

        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
                Toast.makeText(SchedulerActivity.this, "Date changed to" + i2 + "." + i1 + "." + i, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

最佳答案

setOnDateChangeListener方法中设置onViewCreated并在Toast中使用getActivity()。我测试了下面的代码,它正在工作。

public class SchedulerFragment extends Fragment {

    private CalendarView calendarView;

    public SchedulerFragment() {
        // Required empty public constructor
    }


    @Override
    public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
        calendarView = view.findViewById(R.id.scheduler_calendar);
        calendarView.setOnDateChangeListener(new OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull final CalendarView view, final int year, final int month,
                    final int dayOfMonth) {
                Toast.makeText(getActivity(), "Date changed to" + dayOfMonth + "." + month + "." + year, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_scheduler, container, false);
        return root;
    }

}

07-28 13:21