看图

布局
<?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();
}
}
本文介绍了一个简单的Android应用,该应用使用按钮触发日期选择对话框,并将所选日期显示在界面上。通过XML布局文件定义界面元素,并在Java代码中处理时间选择逻辑。
1011





