带有来自 edittext 的预选值的 DatePicker 对话框

DatePicker dialog with preselected value from edittext

我有一个日期选择器对话框,它在单击编辑文本时打开。我想要的是,当我点击 edittext 时,日期选择器对话框应该显示已存在于 edittext 中的日期。

我的代码: Xml代码:

<EditText
            android:id="@+id/dob"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:inputType="date"
            android:hint="Date Of Birth"
            android:textSize="12sp"
         android:drawableRight="@drawable/ic_perm_contact_calendar_black_24dp"
            android:drawableTint="@android:color/holo_orange_light"/>

Java代码:

dob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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-MMM-yyyy"; // your format
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());

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

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

            }
        });

我浏览过许多在线链接,但所有链接都显示了如何在编辑文本中设置日期,但我想要的与此相反。 edittext 中有一个值,日期选择器对话框打开时应将该日期作为预选值。

您需要使用 updateDate(year, month, dayOfMonth) 方法来设置 DatePicker 的日期。

示例代码:

DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
datePicker.updateDate(2018, 9, 5);

您可以使用参数调用 datePickerDialog,

DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener, year, month, day);

这里的月、日、年都是整数。

在下面找到示例代码:

public class MainActivity extends AppCompatActivity {

private EditText chooseDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
final Calendar myCalendar = Calendar.getInstance();
private Date date;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    chooseDate = (EditText) findViewById(R.id.choose_date);

    chooseDate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mDateSetListener = 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);
                    chooseDate.setText(formatter.format(myCalendar.getTime()));
                }

            };
            try {
                if (chooseDate.getText().toString().isEmpty()) {
                    date = new Date();

                } else {
                    date = formatter.parse(chooseDate.getText().toString());
                }
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(MainActivity.this, mDateSetListener, year, month, day).show();
            } catch (ParseException e) {
                Log.d(TAG, "ParseException" + e);
            }
        }
    });
}

}

试试这个

以 MM/DD/YYYY 格式输入日期并单击 Edittext,这样 DatePicker 就会弹出输入的日期。

MainActivity.java

package mydemo.com.datepiker;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    String date = "";
    EditText edittext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edittext = (EditText) findViewById(R.id.edittext);
        edittext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); // Make sure user insert date into edittext in this format.
                Date dateObject;
                try {
                    String dob_var = (edittext.getText().toString());
                    dateObject = formatter.parse(dob_var);
                    date = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);

                    String[] items1 = date.split("/");
                    String d1 = items1[0];
                    String m1 = items1[1];
                    String y1 = items1[2];
                    int d = Integer.parseInt(d1);
                    int m = Integer.parseInt(m1);
                    int y = Integer.parseInt(y1);

                    DatePickerDialog datePicker = new DatePickerDialog(MainActivity.this, 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);
                            edittext.setText(date);
                        }
                    }, y, m - 1, d);
                    datePicker.show();

                } catch (java.text.ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.i("Exception is: ", e.toString());
                }
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mydemo.com.datepiker.MainActivity">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:hint="Enter Date:"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

希望现在对您有所帮助。

编辑文字

 <EditText
                android:id="@+id/txt_Date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:background="@null"
                android:hint="dd/mm/yyyy" />

里面 activity

txt_Date = (EditText) findViewById(R.id.txt_Date);
 txt_Date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layDatePicket.setEnabled(false);
                DatePickerDialog dialog = new DatePickerDialog(Activity.this,
                        listener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH), calender.get(Calendar.DATE));
              // set your date in the above line.
                dialog.show();                                    
            }
        });

在这里实现监听器。

 listener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String date = dayOfMonth + "/" + ((month < 10) ? "0" + month : month) + "/" + year;
                txt_datepicker.setText(date);
            }
        };