2

我有一个按钮可以拉出 DatePicker 片段,但我不知道如何根据选择的日期更改视图。我将 onDateSet 方法放在我的 main.java 中,这是调用片段的活动,目的是更改此方法中的视图,但是当日期更改时它什么也不做,我不确定我做错了什么。

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
    }

我的 MainScreen.java 是

public class MainScreen extends FragmentActivity implements DatePickerDialog.OnDateSetListener {

    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
    }

    public void showDatePickerDialog(View v) {
        DatePickerFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {

        Intent intent = new Intent(this, January_1.class);
        startActivity(intent);
    }
}
4

1 回答 1

1

您应该onDateSet()在 DatePickerFragement 中使用监听器:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Activity activity = getActivity();
        Intent intent = new Intent(activity, January_1.class);
        activity.startActivity(intent);
    }
}

从评论中添加

monthOfYear文档中,您使用了错误的索引:

monthOfYear为与Calendar 兼容而设置的月份 (0-11) 。

所以一月是0,二月是1,等等......
为了避免混淆,我建议使用 Calendar 类中的月份名称和 switch 语句:

Intent intent;
switch(monthOfYear) {
case Calendar.JANUARY:
    intent = new Intent(activity, January_1.class);
    break;
case Calendar.FEBRUARY:
    // etc...
}
activity.startActivity(intent);
于 2012-10-17T20:34:25.193 回答