我在Fragment活动中获取DatePickerFragment的信息时遇到问题。 我有这个代码,摘自Google开发者页面:
public class DatePickerFragment extends DialogFragment {
@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);
ADD add = new ADD();
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) add.getTargetFragment(), year, month, day);
}}
当我收到用户选择的日期时,这是我的MainActivity:
public class ADD extends Fragment implements AdapterView.OnItemSelectedListener, DatePickerDialog.OnDateSetListener {
//code
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Log.w("DatePicker", "Date = " + year);
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(dayOfMonth).append("-")
.append(monthOfYear + 1).append("-")
.append(year).append(" "));
}}
如果以前曾问过这个问题,我会道歉。我一直在这个页面中积极搜索,这个问题仅针对活动而不是片段进行了回答。另外,我必须指出,我不是Java专家。我的直觉告诉我,问题可能出在“回归”中。 DatePickerFragment,但我无法解决问题。
答案 0 :(得分:0)
您可能忘记在setTargetFragment
片段中触发ADD
方法:
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.setTargetFragment(this, 1234);
datePickerFragment.show(getChildFragmentManager(), "DatePickerFragment TAG");
另外用{:
替换onCreateDialog
方法
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(), (DatePickerDialog.OnDateSetListener) getTargetFragment(), year, month, day);