首先上一下效果图
布局比较简单 就是一个button以及textView 下面我就直接放代码吧。
package daviddatepickerdemo.qq986945193.com.daviddatepickerdemo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
/**
* 时间选择器
*/
public class MainActivity extends Activity {
int mYear, mMonth, mDay;
Button btn;
TextView dateDisplay;
final int DATE_DIALOG = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.dateChoose);
dateDisplay = (TextView) findViewById(R.id.dateDisplay);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG);
}
});
final Calendar ca = Calendar.getInstance();
mYear = ca.get(Calendar.YEAR);
mMonth = ca.get(Calendar.MONTH);
mDay = ca.get(Calendar.DAY_OF_MONTH);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
}
return null;
}
/**
* 设置日期 利用StringBuffer追加
*/
public void display() {
dateDisplay.setText(new StringBuffer().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
}
private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
display();
}
};
}
xml 布局:
?xml version="1.0" encoding="utf-8"?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/dateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间显示"/>
<Button
android:id="@+id/dateChoose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择日期" />
</LinearLayout>
铛铛铛铛~ 代码在这儿就结束啦~~ 喜欢的就关注一下我吧~