我有问题宽度DatePickerDialog,因为当它打开并且我转动屏幕(横向/纵向)时,对话框停止。
现在我试图在Bundle中保存对话框的状态,但我真的不知道如何:/
代码:
public class ActivityNeki extends Activity {
private int datY, datM, datD;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
if(savedInstanceState == null){ setTheData(); writeTheData(); }
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("izY", datY);
outState.putInt("izM", datM);
outState.putInt("izD", datD);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
datY = savedInstanceState.getInt("izY");
datM = savedInstanceState.getInt("izM");
datD = savedInstanceState.getInt("izD");
writeTheData();
}
public void onClickOpenDPD(View view) { // the method that is caled from XML onClick
DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override public void onDateSet(DatePicker view, int y, int m, int d) {
datY = y; datM = m; datD = d;
writeTheData();
}
}, datY, datM, datD);
dpd.show();
}
public void setTheData(){
Calendar c = Calendar.getInstance();
datY = c.get(Calendar.YEAR);
datM = c.get(Calendar.MONTH);
datD = c.get(Calendar.DAY_OF_MONTH);
}
public void writeTheData(){
// writes the data in a txtView
}
}
所以,如果任何人知道如何做到这一点,我会给它定价!
提前致谢:)
工作解决方案:(Big tnx to Taig)
public class ActivityNeki extends FragmentActivity {
/**
* the rest of the code
* is the same...
* I only edited this method:
*/
public void onClickOpenDPD(View view) { // the method that is caled from XML onClick
class MyDialogFragment extends DialogFragment {
@Override public void onDestroyView() {
if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null);
super.onDestroyView();
}
@Override public void onCreate(Bundle state) { super.onCreate(state);
setRetainInstance(true);
}
@Override public Dialog onCreateDialog(Bundle state) {
DatePickerDialog dpd = new DatePickerDialog( getActivity(), new DatePickerDialog.OnDateSetListener() {
@Override public void onDateSet(DatePicker view, int y, int m, int d) {
datY = y; datM = m; datD = d;
writeTheData();
} }, datY, datM, datD);
return dpd;
}
}
newDF = new MyDialogFragment();
newDF.show( getSupportFragmentManager(), null );
}
}
答案 0 :(得分:2)
我建议使用DialogFragments,如果这是你的选择。
class MyDialogFragment extends DialogFragment {
@Override
public void onCreate( Bundle state ) {
super.onCreate( state );
setRetainInstance( true );
}
@Override
public Dialog onCreateDialog( Bundle state ) {
return new DatePickerDialog( ... );
}
}
在您的活动中,您可以通过调用new MyDialogFragment().show( getSupportFragmentManager(), null )
启动对话框。对话框将重新打开,您无需自行保留当前选择的方向更改!