我创建了一个更新类变量的类。我正在创建该类的新实例,然后尝试调用get方法。但我得到一个'无法解决方法错误,我不明白为什么。
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);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
}
public int getSelectedDate() {
return selectedDate;
}
}
public void showDatePickerDialog(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
int output = newFragment.getSelectedDate();
}
答案 0 :(得分:1)
错误在这里:
public void showDatePickerDialog(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
int output = newFragment.getSelectedDate();
}
您的变量newFragment
是DialogFragment
。因此,您必须强制转换变量或更改声明:
DatePickerFragment newFragment = new DatePickerFragment();
或
int output = ((DatePickerFragment)newFragment).getSelectedDate();
编辑: 要获取所选日期,您必须使用Listener而不是同步方法。 所以你必须改变你的代码:
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private MyListener listener;
public DatePickerFragment(MyListener listener){
this.listener = listener;
}
@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);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
if(listener!=null){
listener.theDateHasChanged(selectedDate);
}
}
public int getSelectedDate() {
return selectedDate;
}
然后您的活动必须实施MyListener
界面并实施theDateHasChanged
,最后您必须从fragment
实例化activity
所以:
DatePickerFragment newFragment = new DatePickerFragment(this);
答案 1 :(得分:-1)
也许那是因为你的班级是静态的。在java中,您无法创建定义为static的类的实例。对于静态类,可以使用直接调用方法 。();
DatePickerFragment.show(getFragmentManager(),"datePicker");
希望这会有所帮助。 :)