<1.XML布局文件>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <DatePicker android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/data"/> </LinearLayout><2.源代码>
public class MainActivity extends AppCompatActivity { private DatePicker datePicker; private int year,month,date; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //实例化控件 datePicker= (DatePicker) findViewById(R.id.data); //获取当前年分 year=Calendar.getInstance().get(Calendar.YEAR); //获取当前月分 month=Calendar.getInstance().get(Calendar.MONTH); //获取当前日期 date=Calendar.getInstance().get(Calendar.DAY_OF_MONTH); datePicker.init(year, month, date, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { //月份要加1,相信大家都知道,就不细说了 Toast.makeText(MainActivity.this,year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日",Toast.LENGTH_SHORT).show(); } }); } }