Get date from datepicker using dialogfragment

前端 未结 9 856
庸人自扰
庸人自扰 2020-11-28 03:42

I\'m using the google example to insert a datepicker inside my app using a dialogfragment
http://developer.android.com/guide/topics/ui/controls/pickers.html

But

9条回答
  •  春和景丽
    2020-11-28 04:07

    The problem can also be solved without moving the onDateSet method to the parent activity. You just have to tell the DatePickerFragment where to search for the view:

    public 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);
        }
    
        public void onDateSet(DatePicker view, int year, int month, int day) {
            // do some stuff for example write on log and update TextField on activity
            Log.w("DatePicker","Date = " + year);
            ((TextView) getActivity().findViewById(R.id.tf_date)).setText("Date = " + year);
        }
    }
    

    I also changed the target of the cast from EditText to TextView. This way, you can reuse your implementation for different kinds of views, not only for an EditText.

提交回复
热议问题