我正在开发一个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
。
答案 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