Android: DatePicker and DatePicker Dialog

前端 未结 8 570
梦如初夏
梦如初夏 2020-12-24 09:23

I have this code here on the options menu

Dialog dialog = new Dialog(ScheduleActivity.this);
dialog.setTitle(\"Add Event\");
dialog.setContentView(R.layout.         


        
8条回答
  •  我在风中等你
    2020-12-24 10:13

    Old dialogs are deprecated. Implements fragments:

    Migrate your Activity to Fragment Activity:

    public class YourActivity extends FragmentActivity 
    

    Create Fragment Dialog:

    public class TimePickerFragment extends DialogFragment {
    
        private OnDateSetListener listener;
    
        public TimePickerFragment(OnDateSetListener listener) {
            this.listener=listener;
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for 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 TimePickerDialog and return it
            return new DatePickerDialog(getActivity(), listener, year,month,day);
        }
    
    }
    

    Implements interface (package: import android.app.DatePickerDialog.OnDateSetListener):

    public class YourActivity extends FragmentActivity implements OnDateSetListener{
    
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
    
        }
    
    }
    

    Add showDialog function:

    public class YourActivity extends FragmentActivity implements OnDateSetListener{
    
        showDateDialog(){
    
            FragmentManager fm = getSupportFragmentManager();
            TimePickerFragment newFragment = new TimePickerFragment(this);
            newFragment.show(fm, "date_picker");
    
        }
    
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
    
        }
    
    }
    

提交回复
热议问题