看图
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/BT"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="选择时间"/>
</RelativeLayout>
</RelativeLayout>
代码
public class time extends AppCompatActivity {
private Button bt;
@SuppressLint("MissingSuperCall")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
bt = findViewById(R.id.BT);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDatePickDlg();
}
});
}
public void showDatePickDlg () {
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(time.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
time.this.bt.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
}