我是android的新手,并尝试将DatePicker用于我的应用程序。它存在于date.xml文件中。我使用setView(R.layput.date)命令使AlertDialog框显示DatePicker。单击EditText时出现AlertDialog框。现在,当我点击AlertDialog框的保存按钮时,我需要将Date更改为来自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>
这是一组代码AlertDialog框
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;
}
});
答案 0 :(得分:0)
尝试以下代码:
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));