DatePicker的使用
activity_main.xml:
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<DatePicker
android:id="@+id/firstDatePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/firstDatePicker"
android:text="获取当前DatePicker的值"/>
</RelativeLayout>
MainActivity.java:
package com.mcm.datepicker;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
public class MainActivity extends Activity {
private DatePicker datePicker;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datePicker = (DatePicker) findViewById(R.id.firstDatePicker);
button = (Button) findViewById(R.id.button);
ButtonListener buttonListener = new ButtonListener();
button.setOnClickListener(buttonListener);
//datePicker.updateDate(2013, 1, 1);设置datePicker默认时间为2013年2月1日
//不设置的话默认是当前时间
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
int y = datePicker.getYear();
int m = datePicker.getMonth()+1;
int d = datePicker.getDayOfMonth();
System.out.println("当前时间:" + y +"年," + m + "月,"+ d + "日");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}