单击按钮时如何从DatePicker获取日期



我是安卓系统的新手,正在尝试为我的应用程序使用DatePicker。它存在于date.xml文件中。我使用setView(R.layput.date)命令制作了AlertDialog框来显示DatePicker。单击"编辑文本"时会出现"警报"对话框。现在,当我点击AlertDialog框的保存按钮时,我需要从DatePicker将日期更改为字符串。我该怎么做?

这是date.xml文件的一组代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_gravity="center_horizontal"></LinearLayout>
    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_gravity="center_horizontal"
        android:layoutMode="clipBounds" />
</LinearLayout>

这是一组代码Alert对话框

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
final EditText edt = (EditText)findViewById(R.id.invo_date);
edt.setText(dateFormat.format(date));
edt.setInputType(0);
edt.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!one){
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
            AlertDialog.Builder alt = new AlertDialog.Builder(CreateInvoice.this);
            alt.setView(R.layout.date);
            alt.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    one = false;
                }
            });
            alt.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // I need to get date aftre set Date form DatePicker to srting when I click Save button.
                }
            });
            alt.setCancelable(false);
            alt.show();
            one = true;
        }
        return true;
    }
});

尝试以下代码:

int   day  = datePicker.getDayOfMonth();
int   month= datePicker.getMonth() + 1;
int   year = datePicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formatedDate = sdf.format(new Date(year, month, day));

最新更新