问题
Hi I have used this DialogFragment to display date picker in my app
public class DateDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public DateDialogFragment()
{
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar cal=Calendar.getInstance();
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
showSetDate(year,monthOfYear,dayOfMonth);
}
}
public void showSetDate(int year,int month,int day) {
text.setText(year+"/+"+month+"/"+day);
}
If have used the same in my previous apps. Recently it DateDialogFragment behaving strangly. In Eclipse it is showing the error DateDialogFragment should be static.But When I clean the project once. It doesn't showing any error in the project and it runs perfectly. I have gone through this DialogFragment and it confirms that it needs class to be static. But why is it allowing me use this eventhough I haven't give static when I clean the project. This happens recently previously it hasn't show any error like this. The same is not showing any error when I share the project with my team members. Why is it behaving like this..
回答1:
The reason you are seeing this is because Android sometimes needs to instantiate that Fragment on its own. This applies to any Fragment.
When you create a static inner class, that means it is not tied to any specific instance of the outer class. So let's say you have:
public class A {
public static class B {
// ...
}
public class C {
// ...
}
}
In this case, you cannot do new C() from outside A because all instances of C belong to an A object. You can, however, do new B() or new A.B().
The same applies to the fragment; Android cannot do new DateDialogFragment() if the class is not static. The reason you are not getting an error (though Lint should be telling you) is because you are instantiating the DateDialogFragment yourself.
However, if you trigger something like an orientation change and don't recreate the Fragment manually, Android will do it for you. Being unable to do so, it will crash.
If the class is static, however, Android can create an instance of it. Therefore, a nested Fragment class should always be static.
来源:https://stackoverflow.com/questions/15044761/dialogfragment-behaving-unexpectedly