我想显示日期选择器弹出窗口。我找到了一些例子,但我没有得到正确的。我有一个edittext,我希望当我点击edittext时,datepicker对话框应该弹出,设置日期后,日期应该显示在edittext在dd/mm/yyyy格式。请为我提供示例代码或良好的链接。


当前回答

使用片段、MvvmCross和Xamarin的解决方案。安卓

public class EnterTimeView : MvxFragment, DatePickerDialog.IOnDateSetListener
    {            
        private EditText datePickerText;
        public EnterTimeView()
        {
            this.RetainInstance = true;
        }

        public override Android.Views.View OnCreateView(Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState)
        {
            this.HasOptionsMenu = true;

            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.EnterTimeView, container, false);

            datePickerText = view.FindViewById<EditText>(Resource.Id.DatePickerEditText);
            datePickerText.Focusable = false;
            datePickerText.Click += delegate
            {
                var dialog = new DatePickerDialogFragment(Activity, Convert.ToDateTime(datePickerText.Text), this);
                dialog.Show(FragmentManager, "date");
            };

            var set = this.CreateBindingSet<EnterTimeView, EnterTimeViewModel>();    
            set.Bind(datePickerText).To(vm => vm.Date);
            set.Apply();

            return view;
        }   

        public void OnDateSet(Android.Widget.DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString();
        }

        private class DatePickerDialogFragment : Android.Support.V4.App.DialogFragment 
        {
            private readonly Context _context;
            private DateTime _date;
            private readonly DatePickerDialog.IOnDateSetListener _listener;

            public DatePickerDialogFragment(Context context, DateTime date, DatePickerDialog.IOnDateSetListener listener)
            {
                _context = context;
                _date = date;
                _listener = listener;
            }

            public override Dialog OnCreateDialog(Bundle savedState)
            {
                var dialog = new DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
                return dialog;
            }
        }

其他回答

下面是一个针对懒人的Kotlin扩展函数:

fun EditText.transformIntoDatePicker(context: Context, format: String, maxDate: Date? = null) {
    isFocusableInTouchMode = false
    isClickable = true
    isFocusable = false

    val myCalendar = Calendar.getInstance()
    val datePickerOnDataSetListener =
        DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
            myCalendar.set(Calendar.YEAR, year)
            myCalendar.set(Calendar.MONTH, monthOfYear)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            val sdf = SimpleDateFormat(format, Locale.UK)
            setText(sdf.format(myCalendar.time))
        }

    setOnClickListener {
        DatePickerDialog(
            context, datePickerOnDataSetListener, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
            myCalendar.get(Calendar.DAY_OF_MONTH)
        ).run {
            maxDate?.time?.also { datePicker.maxDate = it }
            show()
        }
    }
}

用法:

在活动:

editText.transformIntoDatePicker(this, "MM/dd/yyyy")
editText.transformIntoDatePicker(this, "MM/dd/yyyy", Date())

在片段:

editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy")
editText.transformIntoDatePicker(requireContext(), "MM/dd/yyyy", Date())

这是我怎么做的:类似于选择的答案,但使用一个静态对话框类,所以它更可重用,也使用onFocusChange而不是onClick。

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                DialogFragment datePickerFragment = new DatePickerFragment() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        Log.d(TAG, "onDateSet");
                        Calendar c = Calendar.getInstance();
                        c.set(year, month, day);
                        editText.setText(df.format(c.getTime()));
                        nextField.requestFocus(); //moves the focus to something else after dialog is closed
                    }
                };
                datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
            }
        }
    });

datepicker对话框。

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);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //blah
    }
}
class MyClass implements OnClickListener, OnDateSetListener {   
   EditText editText;
   this.editText = (EditText) findViewById(R.id.editText);
   this.editText.setOnClickListener(this);
   @Override
   public void onClick(View v) {

       DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
       dialog.show();
   }
   @Override
   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
       // this.editText.setText();
   }
}

我对沙玛林的解决方案。基于Linh的MvvmCross的Android:

public class DatePickerEditText : EditText, DatePickerDialog.IOnDateSetListener
{
    IDisposable _clickSubscription;

    public override bool Clickable => true;

    protected DatePickerEditText(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer)
        => Init();

    public DatePickerEditText(Context context) : base(context)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs) 
        : base(context, attrs)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs, int defStyleAttr) 
        : base(context, attrs, defStyleAttr)
        => Init();

    public DatePickerEditText(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) 
        : base(context, attrs, defStyleAttr, defStyleRes)
        => Init();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _clickSubscription?.Dispose();
            _clickSubscription = null;
        }

        base.Dispose(disposing);
    }

    public void OnDateSet(DatePicker view, int year, int month, int dayOfMonth)
        => Text = view.DateTime.ToString("d", CultureInfo.CurrentUICulture);

    void Init()
    {
        SetFocusable(ViewFocusability.NotFocusable);
        _clickSubscription = this.WeakSubscribe(nameof(Click), OnClick);
    }

    void OnClick(object sender, EventArgs e)
    {
        var date = DateTime.Today;
        try
        {
            date = DateTime.Parse(Text, CultureInfo.CurrentUICulture);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }

        var dialog = new DatePickerDialog(Context,
                                          this,
                                          date.Year,
                                          date.Month,
                                          date.Day);
        dialog.Show();
    }
}

来杯香草沙玛林。Android版本只需将WeakSubscribe替换为EditText的Click事件的常规订阅,不要忘记在Dispose方法覆盖中取消订阅。

# 1。我想显示一个datepicker与当前日期预选(我使用butterknife注入)

  @OnClick(R.id.your_view) public void onClickYourView() {

    final Calendar myCalendar = Calendar.getInstance();
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String myFormat = "dd MMMM yyyy"; // your format
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());

        your_view.setText(sdf.format(myCalendar.getTime()));
      }

    };
    new DatePickerDialog(mContext, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();

  }

2. 如果您想预选日期,请将最后一部分替换为

new DatePickerDialog(mContext, date, 1990, 0, 1).show();

然后你可以使用myCalendar变量或直接在视图上的文本来获取它。