1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.view.View; 4 import android.view.View.OnClickListener; 5 import android.widget.Button; 6 import android.widget.DatePicker; 7 8 public class MainActivity extends Activity { 9 private DatePicker datepicker; 10 private Button button; 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_main); 14 15 datepicker = (DatePicker) findViewById(R.id.datepicker); 16 17 datepicker.updateDate(2013, 8, 11);//设置默认的时间,不设置默认的就是当前时间,8表示的是7月份,因为java中月份是从0开始的 18 button = (Button) findViewById(R.id.button); 19 button.setOnClickListener(new ButtonListener()); 20 21 } 22 class ButtonListener implements OnClickListener{ 23 public void onClick(View v) { 24 int year = datepicker.getYear(); 25 int month = datepicker.getMonth(); 26 int date = datepicker.getDayOfMonth(); 27 System.out.println("year="+year+",month="+month+",date="+date); 28 } 29 30 } 31 32 }
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" > 10 11 12 <DatePicker 13 android:id="@+id/datepicker" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 /> 17 18 <Button 19 android:id="@+id/button" 20 android:layout_width="wrap_content" 21 android:layout_height="wrap_content" 22 android:layout_below="@id/datepicker" 23 android:text="获取当前时间" 24 />" 25 26 </RelativeLayout>