2016-05-13 72 views
0

告訴我我做錯了什麼。從https://www.youtube.com/watch?v=ZHLCfqN-60A複製代碼,我看到類似的東西。 這就是:在CalendarView類對象上找不到類

的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> 

任何建議? 我將不勝感激。

回答

1

您已經添加了涉及生命週期方法之外的UI元素的代碼。 由於在初始化時沒有將視圖元素附加到類上,所以會出現錯誤。

下面的代碼塊應該在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(); 
    } 
}); 
+0

Thx很多! 對不起,我忘了添加occuring錯誤..:/ – Azbesciak

相關問題