ChatGPT解决这个技术问题 Extra ChatGPT

Datepicker:单击edittext时如何弹出日期选择器

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

希望它对多个edittext也有帮助。 gist.github.com/pratikbutani/036e73e26139096e3b0ba91f85e23d85

T
Teocci

在 XML 文件中试试这个:

<EditText
    android:id="@+id/Birthday"
    custom:font="@string/font_avenir_book"
    android:clickable="false" 
    android:cursorVisible="false" 
    android:focusable="false" 
    android:focusableInTouchMode="false"
    android:hint="@string/birthday"/>

这在Java文件中:

public class MainActivity extends AppCompatActivity {
    final Calendar myCalendar= Calendar.getInstance();
    EditText editText;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText=(EditText) findViewById(R.id.BirthDate);
        DatePickerDialog.OnDateSetListener date =new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int day) {
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH,month);
                myCalendar.set(Calendar.DAY_OF_MONTH,day);
                updateLabel();
            }
        };
        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DatePickerDialog(MainActivity.this,date,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
    }

    private void updateLabel(){
        String myFormat="MM/dd/yy";
        SimpleDateFormat dateFormat=new SimpleDateFormat(myFormat, Locale.US);
        editText.setText(dateFormat.format(myCalendar.getTime()));
    }
}

EditText 的 xml 文件中添加 android:focusable="false" 以允许单次触摸。


你能告诉我那个 new_split.this 是什么吗?
这对我不起作用。 :( 我有错误,我不知道如何用 updateLabel 方法摆脱。
使用 editText.setOnFocusChangeListener 代替,在第一次点击时工作
我通过使用 android:focusable="false"onclicklistner 解决了这个问题
可能也想设置 android:longClickable="false"。否则,用户可以在该字段上调出粘贴选项(从而输入无效日期)。
S
Shridutt Kothari

无法让这些工作中的任何一个工作,所以会添加我的一个,以防万一它有帮助。

public class MyEditTextDatePicker  implements OnClickListener, OnDateSetListener {   
EditText _editText;
private int _day;
private int _month;
private int _birthYear;
private Context _context;

public MyEditTextDatePicker(Context context, int editTextViewID)
{       
    Activity act = (Activity)context;
    this._editText = (EditText)act.findViewById(editTextViewID);
    this._editText.setOnClickListener(this);
    this._context = context;
}

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    _birthYear = year;
    _month = monthOfYear;
    _day = dayOfMonth;
    updateDisplay();
}
@Override
public void onClick(View v) {
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

    DatePickerDialog dialog = new DatePickerDialog(_context, this,
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
    dialog.show();

}

// updates the date in the birth date EditText
private void updateDisplay() {

    _editText.setText(new StringBuilder()
    // Month is 0 based so add 1
    .append(_day).append("/").append(_month + 1).append("/").append(_birthYear).append(" "));
}
}

还有其他没有提到的东西。确保将以下内容放在 EditText xml 上。

android:focusable="false"

否则就像我的情况一样,键盘会不断弹出。希望这可以帮助某人


惊人的!!另外:不适用于片段视图。对于 Fragments 将构造函数参数更改为 EditText 对象而不是资源 ID..
最完美的答案我还在日历日历行之后添加了 if(_birthYear!=0) calendar.set(_birthYear,_month,_day); 以在用户再次按下时加载最后选择的日期
M
Miral Dhokiya
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();
   }
}

使 onDateSet 不在 On Click 内部调用,而是在构造 callBack 对象时调用它,该对象应作为第二个参数 callBack = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(getApplicationContext(),year+ " "+monthOfYear+" "+dayOfMonth,Toast.LENGTH_LONG).show(); } };
D
Drunken Daddy

这是一个针对懒人的 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())

@moyo 我在上一个 android 版本上没有发现任何问题。检查您的项目中是否设置了其他导致它的配置。
这有效,但它也将 datepicker 上的最大日期设置为 date(),你将如何删除 maxdate?
不要在函数 transformIntoDatePicker 中传递 maxDate 参数
S
Sumoanand

还有另一种更好的可重用方式:

创建一个类:

class setDate implements OnFocusChangeListener, OnDateSetListener {   

       private EditText editText;
       private Calendar myCalendar;

       public setDate(EditText editText, Context ctx){
           this.editText = editText;
           this.editText.setOnFocusChangeListener(this);
           myCalendar = Calendar.getInstance();
       }

       @Override
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)     {
           // this.editText.setText();

            String myFormat = "MMM dd, yyyy"; //In which you need put here
            SimpleDateFormat sdformat = new SimpleDateFormat(myFormat, Locale.US);
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            editText.setText(sdformat.format(myCalendar.getTime()));

       }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
             new DatePickerDialog(ctx, this, myCalendar
                       .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                       myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        }

    }

然后在 onCreate 函数下调用这个类:

    EditText editTextFromDate = (EditText) findViewById(R.id.editTextFromDate);
    setDate fromDate = new setDate(editTextFromDate, this);

类签名应该看起来如何: class setDate implements View.OnFocusChangeListener, DatePickerDialog.OnDateSetListener {
类 setDate 实现 View.OnFocusChangeListener、TimePickerDialog.OnDateSetListener
您的解决方案使用片段对我有用。我只是将“this”更改为“getContext()”。
此外,您需要设置一个私有变量并从构造函数中设置它。 “私有上下文 ctx;”。
此外,我在释放键盘时遇到了一些问题。所以,我添加了“v.clearFocus();”在 onFocusChange 处理程序中。
d
dferenc
<EditText
    android:id="@+id/date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="DD/MM/YYYY"
    android:inputType="date"
    android:focusable="false"/>

<EditText
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="00:00"
    android:inputType="time"
    android:focusable="false"/>

JAVA文件

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText selectDate,selectTime;
    private int mYear, mMonth, mDay, mHour, mMinute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectDate=(EditText)findViewById(R.id.date);
        selectTime=(EditText)findViewById(R.id.time);

        selectDate.setOnClickListener(this);
        selectTime.setOnClickListener(this);




    }

    @Override
    public void onClick(View view) {

        if (view == selectDate) {
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);


            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {

                            selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
        if (view == selectTime) {

            // Get Current Time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {

                            selectTime.setText(hourOfDay + ":" + minute);
                        }
                    }, mHour, mMinute, false);
            timePickerDialog.show();
        }
    }
}

D
Daniel Jonker

我就是这样做的:类似于选择的答案,但使用静态对话框类,因此它更可重用,并且还使用 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");
            }
        }
    });

和日期选择器对话框。

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

C
CodyEngel

选择的答案对我来说不太有效,因为我必须点击一次 EditText 框,然后在 OnClickListener 触发之前再次点击它。我可以通过用 OnTouchListener 替换 OnClickListener 来解决这个问题,以防万一有人遇到类似的问题,我的代码如下所示:

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

};
edittext.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public void onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            new DatePickerDialog(classname.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    }
});

private void updateLabel() {

    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

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

这个问题也可以通过这个来解决:editTextView.setFocusable(false);
O
OWADVL

#1。我想显示一个带有当前日期的日期选择器(我使用黄油刀进行注射)

  @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 变量或直接在视图中获取它。


e
erluxman
 selectDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog  mdiDialog =new DatePickerDialog(mContext,new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Toast.makeText(getApplicationContext(),year+ " "+monthOfYear+" "+dayOfMonth,Toast.LENGTH_LONG).show();


                    }
                }, year, month, date);
                mdiDialog.show();

            }

        });

我不太确定,可能有另一种方法可以覆盖或者你可以连接
最后一个选项是使用获得的年月日初始化日历并以所需格式获取日期
哦,您可以使用方法 private String get2DigitValue(int value){ return int>9?int+"":"0"+int}
G
Gowthaman M

使用数据绑定:

<EditText
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:focusable="false"
  android:onClick="@{() -> viewModel.onDateEditTextClicked()}"
  android:hint="@string/hint_date"
  android:imeOptions="actionDone"
  android:inputType="none"
  android:maxLines="1"
  android:text="@={viewModel.filterDate}" />

(见 focusableinputTypeonClick

内部视图模型:

public void onDateEditTextClicked() {
    // do something
}

这对任何人都有效吗?我尝试使用这种方法,但没有调用 onClick 方法。但是当我在 viewModel 中编写传统的 onClickListener 时,它就可以工作了。
B
Brad Hasha
import android.app.DatePickerDialog;
import android.content.Context;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class DatePickerHelper {

private final Calendar calendar = Calendar.getInstance();
private final String dateFormat = "MM/dd/yy";
private TextView textView = null;

public DatePickerHelper(final Context context, TextView textView) {
    this.textView = textView;

    // Setup on click listener if the TextView is not null
    if (textView != null) {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDatePickerDialog(context).show();
            }
        });
    }
}

/**
 * Return a new date picker listener tied to the specified TextView field
 * @return
 */
private DatePickerDialog.OnDateSetListener getOnDateSetListener() {
    return new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
            textView.setText(sdf.format(calendar.getTime()));
        }
    };
}

/**
 * Return new DatePickerDialog for field
 * @param context
 * @return
 */
private DatePickerDialog getDatePickerDialog(Context context) {
    return new DatePickerDialog(context, getOnDateSetListener(), calendar
            .get(Calendar.YEAR), calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH));
}

}

用法:

  DatePickerHelper assessmentDueDateHelper = new DatePickerHelper(AssessmentsDetailActivity.this,
            (TextView) findViewById(R.id.assessmentDueDateEditText));

A
Abhishek Sengupta

使用这个简单的技术来做到这一点:

第 1 步:创建片段对话框

public class DatePickerFragmentDialog  extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
    }

}

第 2 步:在所需的活动中遵循此

活动必须实现: DatePickerDialog.OnDateSetListener 在按钮上设置 onClickListener: DialogFragment datePicker = new DatePickerFragmentDialog(); datePicker.show(getSupportFragmentManager(), "自定义日期选择器");

第 3 步:覆盖 OnDateSetListener

public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        @SuppressLint("SimpleDateFormat") DateFormat dateFormat = new 
        SimpleDateFormat("MM/dd/yyyy");
        String currentDateString = dateFormat.format(calendar.getTime());

        tvPaymentDate.setText(currentDateString);
    }

因此我们可以对日期使用任何格式:)


b
ben

使用片段、MvvmCross 和 Xamarin.Android 的解决方案

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

L
Linh

我的表演课 DatePicker。我可以用于 EditTextTextViewButton

import android.app.DatePickerDialog;
import android.content.Context;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TextViewDatePicker
        implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
    private DatePickerDialog mDatePickerDialog;
    private TextView mView;
    private Context mContext;
    private long mMinDate;
    private long mMaxDate;

    public TextViewDatePicker(Context context, TextView view) {
        this(context, view, 0, 0);
    }

    public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
        mView = view;
        mView.setOnClickListener(this);
        mView.setFocusable(false);

        mContext = context;
        mMinDate = minDate;
        mMaxDate = maxDate;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        Date date = calendar.getTime();

        SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
        mView.setText(formatter.format(date));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        if (mMinDate != 0) {
            mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
        }
        if (mMaxDate != 0) {
            mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
        }
        mDatePickerDialog.show();
    }

    public DatePickerDialog getDatePickerDialog() {
        return mDatePickerDialog;
    }

    public void setMinDate(long minDate) {
        mMinDate = minDate;
    }

    public void setMaxDate(long maxDate) {
        mMaxDate = maxDate;
    }
}

使用

EditText myEditText = findViewById(R.id.myEditText);
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText, minDate, maxDate);
//TextViewDatePicker editTextDatePicker = new TextViewDatePicker(context, myEditText); //without min date, max date

A
Allen

Kotlin 移植,调用 setDatePicker 函数

private fun setDatePicker(dateEditText: EditText) {

    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)
        updateLabel(myCalendar, dateEditText)
    }

    dateEditText.setOnClickListener {
        DatePickerDialog(this@YourActivityName, datePickerOnDataSetListener, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show()
    }
}

private fun updateLabel(myCalendar: Calendar, dateEditText: EditText) {
    val myFormat: String = "dd-MMM-yyyy"
    val sdf = SimpleDateFormat(myFormat, Locale.UK)
    dateEditText.setText(sdf.format(myCalendar.time))
}

A
Aakash

日期选择器对话框

                Calendar c=Calendar.getInstance();
                Integer month=c.get(Calendar.MONTH);
                Integer day=c.get(Calendar.DAY_OF_MONTH);
                Integer year=c.get(Calendar.YEAR);

                DatePickerDialog datePickerDialog =new DatePickerDialog(Expenture_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        et_from.setText(dayOfMonth+"/"+month+"/"+year);
                    }
                },year,month,day);
                datePickerDialog.show();

m
mehrdadjg

我已经尝试了所有建议的方法,但它们都有自己的问题。

我认为最好的解决方案是使用如下框架布局:

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                .... />

            <View
                android:id="@+id/invisible_click_watcher"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clickable="true" />

</FrameLayout>

然后添加在@Android 的答案中精美编写的 DatePickerDialog 代码。


M
Mark Proctor

我认为最好覆盖 EditText 类...

public class EditTextDP extends android.support.v7.widget.AppCompatEditText implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    public EditTextDP(Context context) {
        super(context);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        setFocusable(false);
    }

    public EditTextDP(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(this);
        setFocusable(false);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        setText(new StringBuilder().append(dayOfMonth).append("/").append(monthOfYear + 1).append("/").append(year));
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
        DatePickerDialog dialog = new DatePickerDialog(getContext(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
}

并在 XML 中使用它...

            <*.*.*.EditTextDP
                android:id="@+id/c1_dob_hm"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/round_edittext_white"
                android:ems="10"
                android:padding="8dp">

            </*.*.*.EditTextDP>

P
Praveen
editText1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DatePickerDialog.OnDateSetListener dpd = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {

                    int s = monthOfYear + 1;
                    String a = dayOfMonth + "/" + s + "/" + year;
                    editText1.setText(a);
                }
            };

            Time date = new Time();
            DatePickerDialog d = new DatePickerDialog(UpdateStore.this, dpd, date.year, date.month, date.monthDay);
            d.show();

        }
    });

G
Gowthaman M

用这个

your_edittext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {

                    final Calendar calendar = Calendar.getInstance();
                    int yy = calendar.get(Calendar.YEAR);
                    int mm = calendar.get(Calendar.MONTH);
                    int dd = calendar.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1)
                                    + "/" + String.valueOf(year);
                            your_edittext.setText(date);
                        }
                    }, yy, mm, dd);
                    datePicker.show();
                }
            });

m
moyo

使用 @DrunkenDaddy 扩展功能,至少在我的情况下(以编程方式创建 EditText),它在第一次单击时显示键盘,然后在第二次单击时显示日期选择器。

显然,将 isFocusable 和 isFocusableInTouchMode 设置为 false 是无关紧要的,因为第一次单击总是被 EditText 解释为焦点更改。因此,当 EditText 获得焦点时,我不得不触发一次点击。现在它按预期工作:第一次单击时,它直接打开日期选择器,而不是键盘(感谢将 showSoftInputOnFocus 设置为 false):

fun EditText.transformIntoDatePicker(context: Context, format: String = "dd/MM/yyyy", maxDate: Date? = null) {
    isClickable = true
    showSoftInputOnFocus = false
    isCursorVisible = false

    setOnFocusChangeListener { _, hasFocus ->  if (hasFocus) callOnClick()}

    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.getDefault())
            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()
    }
}

s
sarjeet singh

如果您需要所有活动的单个函数,调用该函数时将打开日期选择器,然后返回我选择的日期,然后为所有活动创建一个界面

public interface OnDatePickerLitionarCallBack {

    void DatePicker(String selectedDate);
}

然后在活动中调用接口

 public class MapsActivity extends FragmentActivity implements OnDatePickerLitionarCallBack {
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        findViewById(R.id.date_pick).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                date_Picker(MapsActivity.this,MapsActivity.this);
            }
        });
    }
     @Override
        public void DatePicker(String selectedDate) {
        
    
        }
    }

在实现接口之后创建一个公共公共类来访问任何活动或片段

public class Commons{

    public static void date_Picker(Context context, OnDatePickerLitionarCallBack onDatePickerLitionarCallBack) {
        final java.util.Calendar myCalendar = java.util.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(java.util.Calendar.YEAR, year);
                myCalendar.set(java.util.Calendar.MONTH, monthOfYear);
                myCalendar.set(java.util.Calendar.DAY_OF_MONTH, dayOfMonth);
                String myFormat = "dd,MMM yyyy"; //In which you need put here
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(myFormat, Locale.US);
   
                onDatePickerLitionarCallBack.DatePicker(sdf.format(myCalendar.getTime()));

            }
        };
        DatePickerDialog datePickerDialog = new DatePickerDialog(context, date, myCalendar
                .get(java.util.Calendar.YEAR), myCalendar.get(java.util.Calendar.MONTH),
                myCalendar.get(java.util.Calendar.DAY_OF_MONTH));


        datePickerDialog.show();

    }
}

M
Martin Tournoij
public class DatePickerActivity extends AppCompatActivity {
    Button button;
    static TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.btn_click);
        textView= (TextView) findViewById(R.id.txt_date);



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment=new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datepicker");
            }
        });

    }

    public class DatePickerFragment extends DialogFragment implements    DatePickerDialog.OnDateSetListener{
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int  day) {
            String years=""+year;
            String months=""+(monthOfYear+1);
            String days=""+day;
            if(monthOfYear>=0 && monthOfYear<9){
                months="0"+(monthOfYear+1);
            }
            if(day>0 && day<10){
                days="0"+day;

            }
            textView.setText(days+"/"+months+"/"+years);


        }

        @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);
            DatePickerDialog datePickerDialog=null;
            datePickerDialog=new DatePickerDialog(getActivity(), this, year,  month, day);

            return datePickerDialog;
        }

    }

}

G
Gowthaman M

尝试这个

btn=(Button)findViewById(R.id.chs);
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setCanceledOnTouchOutside(true);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.setContentView(R.layout.datepickerdialog);
            dp=(DatePicker) dialog.findViewById(R.id.btp);
            dialog.show();
            ok=(Button)dialog.findViewById(R.id.btn1);
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }

    });

与代码示例一起对您的答案进行一些解释会很有帮助。
J
Jaimin Mehta

editText.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(final View v) {
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);


        final DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                new DatePickerDialog.OnDateSetListener() {
                    String fmonth, fDate;
                    int month;


                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {


                        try {
                            if (monthOfYear < 10 && dayOfMonth < 10) {

                                fmonth = "0" + monthOfYear;
                                month = Integer.parseInt(fmonth) + 1;
                                fDate = "0" + dayOfMonth;
                                String paddedMonth = String.format("%02d", month);
                                editText.setText(fDate + "/" + paddedMonth + "/" + year);

                            } else {

                                fmonth = "0" + monthOfYear;
                                month = Integer.parseInt(fmonth) + 1;
                                String paddedMonth = String.format("%02d", month);
                                editText.setText(dayOfMonth + "/" + paddedMonth + "/" + year);
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                }, mYear, mMonth, mDay);
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        datePickerDialog.show();


    }


});

A
Adam Noor

将这 4 行放在(EditText、AppCompatEditText)上。它不会显示键盘。然后在 clicklistener 上,您可以显示 datePicker

android:clickable="false" 
   android:cursorVisible="false" 
   android:focusable="false" 
   android:focusableInTouchMode="false"

R
Robert

尝试这个:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

DataPickerListener listener;

public DatePickerFragment(DataPickerListener l) {
    listener = l;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the date 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);

    return new DatePickerDialog(getActivity(),
            AlertDialog.THEME_HOLO_LIGHT, this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {

    month = month + 1;
    String stringOfDate = day + "-" + month + "-" + year;
    listener.setDate(stringOfDate);
    Util.Log(stringOfDate);
}

@Override
public void onCancel(DialogInterface dialog) {
    // TODO Auto-generated method stub
    super.onCancel(dialog);
    listener.cancel();
}

public static interface DataPickerListener {
    void setDate(String date);

    void cancel();
}
}
// use this function to open datePicker popup

DialogFragment newFragment;

public void pickDate() {
    if (newFragment == null)
        newFragment = new DatePickerFragment(new PickDateListener());
    newFragment.show(getFragmentManager(), "Date Picker");
}

class PickDateListener implements DataPickerListener {

    @Override
    public void setDate(String date) {
        createSpiner(date);
        onetouch = false;
    }

    @Override
    public void cancel() {
        onetouch = false;
    }

}

U
Umberto Mignozzetti
    EditText text = (EditText) findViewById(R.id.editText);

    text.setOnClickListener(new OnClickListener(){
       @RequiresApi(api = Build.VERSION_CODES.N)
       @Override
       public void onClick(View view) {

             DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
               @Override
               public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                   String date = i2 + "/" + (++i1) + "/" + i;
                   text.setText(date);
                }
        },year,month,date);
       }
    });  

    datePickerDialog.show();

您还可以通过这些语句设置最小日期和最大日期。

   datepickerDialoge.getDatepicker().setMinDate(long Date);

   datepickerDialoge.getDatepicker().setMaxDate(long Date);

注意:在 datepickerDialog.show() 之前添加这些行;声明你会得到这样的日期=12/2/2017。

我希望我的回答会有所帮助。


L
Lexo

这在 2020 年 1 月对我有用

XML 部分:

  <EditText
            android:id="@+id/etDOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:editable="false"
            android:ems="10"
            android:hint="Enter Your Date of Birth" />

Java部分:

         final Calendar myCalendar = Calendar.getInstance();

         userDOBView  = (EditText)findViewById(R.id.etDOB);


    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener(){
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int  dayOfMonth) {
             myCalendar.set(Calendar.YEAR, year);
             myCalendar.set(Calendar.MONTH, monthOfYear);
             myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
             updateLabel();
      }
    };

    userDOBView.setOnTouchListener(new View.OnTouchListener(){
      @Override
      public boolean onTouch(View v, MotionEvent event){
       if(event.getAction() == MotionEvent.ACTION_DOWN){
         new DatePickerDialog("YourClassName".this, date, 
             myCalendar.get(Calendar.YEAR), 
             myCalendar.get(Calendar.MONTH),         
             myCalendar.get(Calendar.DAY_OF_MONTH)).show();
          }
          return true;
       }
    });
private void updateLabel() {
  String myFormat = "MM/dd/yyyy"; //In which you need put here
  SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

  // edittext.setText(sdf.format(myCalendar.getTime()));
  userDOBView.setText(sdf.format(myCalendar.getTime()));
} 

不要发布已弃用的答案。

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅