android - 从日历中选择日期并将其显示在 TextView 中的最佳方法

标签 android android-fragments android-calendar

我已经搜索了很多,需要知道从日历中选择日期的最佳方法,我已经在尝试一个 fragment ,例如

FragmentManager 管理器=getFragmentManager();
FragmentTransaction 事务=manager.beginTransaction();

DialogFragment fragment =新 DatePickerDialogFragment(MainActivity.this);
fragment .show(事务,“date_dialog”);

但在进口方面有错误,因为我相信它们是相互矛盾的......
真的需要一个出路,有没有人有一个好的解决方案,请让我知道我需要它!

最佳答案

我喜欢用 Dialog 来做这件事。
首先,设置android:focusable="false"在您的 EditText 上在你的 xml 中。

然后你可以尝试这样的事情:

yourEditText = (EditText) findViewById(R.id.yourEditTextID);
        yourEditText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // To show current date in the datepicker
                Calendar mcurrentDate = Calendar.getInstance();
                mYear = mcurrentDate.get(Calendar.YEAR);
                mMonth = mcurrentDate.get(Calendar.MONTH);
                mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog mDatePicker = new DatePickerDialog(yourActivity.this, new OnDateSetListener() {
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                        Calendar myCalendar = Calendar.getInstance();
                        myCalendar.set(Calendar.YEAR, selectedyear);
                        myCalendar.set(Calendar.MONTH, selectedmonth);
                        myCalendar.set(Calendar.DAY_OF_MONTH, selectedday);
                        String myFormat = "dd/MM/yy"; //Change as you need
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
                        yourEditText.setText(sdf.format(myCalendar.getTime()));

                        mDay = selectedday;
                        mMonth = selectedmonth;
                        mYear = selectedyear;
                    }
                }, mYear, mMonth, mDay);
                //mDatePicker.setTitle("Select date");
                mDatePicker.show();
            }
        });

其中 mYear、mMonth 和 mDay 是全局整数。

关于android - 从日历中选择日期并将其显示在 TextView 中的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21408050/

相关文章:

Android 日历 View 。连续显示月份

java - 如何以天为单位显示毫秒数 :hours:min:seconds

java - ARCore session 未重新启动

android - View Pager Crash Null Pointer Exception 由于导航回旧 fragment - Android

android - UI元素是在Fragment还是FragmentActivity中发起的?

java - 如何从 Android Studio 中 fragment 的 XML 布局导航到相应的 java 类?

java - 有没有另一种方法可以在 Android 日历选择器中添加天数

android - 统一安卓: no non-static method with name

android - 失败 [INSTALL_FAILED_OLDER_SDK] Android Studio

Android - ViewModel、LiveData、Room 和 Retrofit 以及协程在 kotlin 中组合在一起