datepicker测试activity
public class Ch4_DatePickerActivity extends AppCompatActivity
implements View
.OnClickListener, DatePickerDialog.OnDateSetListener {
private TextView tv_date;
private DatePicker dp_date;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datepicker_ch4);
tv_date = findViewById(R.id.ch4_tv_date);
dp_date = findViewById(R.id.ch4_dp_date);
findViewById(R.id.ch4_btn_date).setOnClickListener(this);
findViewById(R.id.ch4_btn_ok).setOnClickListener(this);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String desc = String.format("您选择的日期是%d年%d月%d日",
year, month + 1, dayOfMonth);
tv_date.setText(desc);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.ch4_btn_date) {
Calendar calendar = Calendar.getInstance();
DatePickerDialog dialog = new DatePickerDialog(this, this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
dialog.show();
} else if (v.getId() == R.id.ch4_btn_ok) {
String desc = String.format("您选择的日期是%d年%d月%d日",
dp_date.getYear(), dp_date.getMonth() + 1, dp_date.getDayOfMonth());
tv_date.setText(desc);
}
}
}
布局文件
<?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:orientation="vertical">
<Button
android:id="@+id/ch4_btn_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请选择日期"
android:textColor="@color/black"
android:textSize="17sp" />
<DatePicker
android:id="@+id/ch4_dp_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner"
android:gravity="center"
android:spinnersShown="true" />
<Button
android:id="@+id/ch4_btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="确 定"
android:textColor="@color/black"
android:textSize="17sp" />
<TextView
android:id="@+id/ch4_tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
点击日期选择器