下午好,我是Android Studio开发新手,我正在开发一个应用程序,需要在其中一个Fragments中创建日历。
我试图在我的片段中创建一个CalendarView,但是setContentView方法和其他方法都以红色突出显示,我做错了什么?
public class CalendarFragment extends Fragment {
private CalendarView calendarView;
public CalendarFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_calendar);
CalendarView calendarView = findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year,
int month, int dayOfMonth) {
int mYear = year;
int mMonth = month;
int mDay = dayOfMonth;
String selectedDate = new StringBuilder().append(mMonth + 1)
.append("-").append(mDay).append("-").append(mYear)
.append(" ").toString();
Toast.makeText(getApplicationContext(), selectedDate, Toast.LENGTH_LONG).show();
}
});
}
}
1条答案
按热度按时间jrcvhitl1#
"你可以这样尝试"
在这里,您需要在
onCreateView
中获取CalendarView
并返回view1
,否则将得到java.lang.NullPointerException:
错误,类似于View view1 = inflater.inflate(R.layout.fragment_calendar, container, false);