class 未在 CalendarView class 对象上找到

class not found on CalendarView class object

告诉我我做错了什么。从 https://www.youtube.com/watch?v=ZHLCfqN-60A 复制粘贴该代码,我看到类似这样的内容。 这是:

Java

package com.example.witek.calendarexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CalendarView;
import android.widget.Toast;

public class CalendarExampleActivity extends AppCompatActivity {
    CalendarView calendarView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar_example);
    }
    calendarView = (CalendarView) findViewById(R.id.cal);
    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {


            Toast.makeText(getApplicationContext(), "Selected Date:\n" + "Day = " + i2 + "\n" + "Month = " + i1 + "\n" + "Year = " + i, Toast.LENGTH_LONG).show();
        }
    });

}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.witek.calendarexample.CalendarExampleActivity">

    <CalendarView android:id="@+id/cal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

有什么建议吗? 我将不胜感激。

您在生命周期方法之外添加了引用 UI 元素的代码。 由于在初始化时没有视图元素附加到 class,因此您会收到错误消息。

下面的代码块应该在 onCreate 方法中。

calendarView = (CalendarView) findViewById(R.id.cal);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
    @Override
    public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {


        Toast.makeText(getApplicationContext(), "Selected Date:\n" + "Day = " + i2 + "\n" + "Month = " + i1 + "\n" + "Year = " + i, Toast.LENGTH_LONG).show();
    }
});