对我有帮助的博客点击打开链接这个真的不难,看别人的教程就ok了,我就贴个代码。

  1. public class MainActivity extends ActionBarActivity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. Button btnDate = (Button) findViewById(R.id.btnDate);
  7. btnDate.setOnClickListener(new View.OnClickListener() {
  8. @Override
  9. public void onClick(View v) {
  10. onCreateDialog().show();//直接调用下面的函数就可以弹出日期选择框
  11. }
  12. });
  13. }
  14. protected Dialog onCreateDialog(){
  15. Calendar calendar = Calendar.getInstance();
  16. Dialog dialog = null;
  17. DatePickerDialog.OnDateSetListener dateListener =
  18. new DatePickerDialog.OnDateSetListener() {
  19. @Override
  20. public void onDateSet(DatePicker datePicker,
  21. int year, int month, int dayOfMonth) {
  22. EditText editText =
  23. (EditText) findViewById(R.id.editText);
  24. //Calendar月份是从0开始,所以month要加1
  25. editText.setText( year + "-" +
  26. (month+1) + "-" + dayOfMonth );
  27. }
  28. };
  29. dialog = new DatePickerDialog(this,
  30. dateListener,
  31. calendar.get(Calendar.YEAR),
  32. calendar.get(Calendar.MONTH),
  33. calendar.get(Calendar.DAY_OF_MONTH));
  34. return dialog;
  35. }

再贴一个布局文件

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. tools:context=".MainActivity">
  6. <LinearLayout
  7. android:orientation="horizontal"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content">
  10. <Button android:id="@+id/btnDate"
  11. android:text="日期选择"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"/>
  14. <EditText android:id="@+id/editText"
  15. android:layout_width="250px"
  16. android:layout_height="wrap_content"
  17. android:editable="false"
  18. android:cursorVisible="false"/>
  19. </LinearLayout>
  20. </RelativeLayout>