如何在FragmentActivity中使用`DatePickerDialog`?

时间:2013-07-19 10:16:03

标签: android

我正在开发一个Android应用程序,我在设计布局时遇到了问题:

我在片段中有这个代码:

DatePickerDialog dialog = 
     DatePickerDialog(getActivity(), mDateSetListener, mYear, mMonth, mDay);

我得到了这个编译错误:

The method DatePickerDialog(FragmentActivity, DatePickerDialog.OnDateSetListener, int, int, int) is undefined for the type UserProfileFragment  UserProfileFragment.java    

如何在片段中使用DatePickerDialog

顺便说一句,“父”活动延伸SlidingFragmentActivity

2 个答案:

答案 0 :(得分:4)

您错过了new关键字

DatePickerDialog dialog = new
     DatePickerDialog(getActivity(), mDateSetListener, mYear, mMonth, mDay);

答案 1 :(得分:1)

我认为在DatePickerFragment中使用DatePickerDialog(又名Fragment)并将其添加到FragmentManager(参见getSupportFragmentManager()

像这样你可以在显示轮换中存活(参见Prevent dialog dismissal on screen rotation in Android

片段本身

public static 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 month, int day) {
        // Do something with the date chosen by the user
    }
}

显示DatePickerFragment

的代码
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

别忘了将extends Activity更改为extends FragmentActivity