Android Studio 无法在片段内创建CalendarView

4zcjmb1e  于 2023-01-26  发布在  Android
关注(0)|答案(1)|浏览(117)

下午好,我是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();
            }
        });
    }
}
jrcvhitl

jrcvhitl1#

"你可以这样尝试"

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view1 = inflater.inflate(R.layout.fragment_calendar, container, false);
        calendarView = view1.findViewById(R.id.calendarView);
        calendarView.setOnDateChangeListener((view, year, month, 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(getContext(), selectedDate, Toast.LENGTH_LONG).show();
        });

        return view1;

    }

在这里,您需要在onCreateView中获取CalendarView并返回view1,否则将得到java.lang.NullPointerException:错误,类似于View view1 = inflater.inflate(R.layout.fragment_calendar, container, false);

相关问题