如何在同一对话框中显示日期选择器和时间选择器?
如果我使用
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
应该在MainAcitiviy.java上做什么
我是android新手。我搜索了但什么都没得到,
最佳答案
您可以将Date Picker和Time Picker都放在布局XML中:Referring this
date_time_picker.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="match_parent">
<DatePicker
android:id="@+id/date_picker"
android:layout_width="match_parent"
android:calendarViewShown="true"
android:spinnersShown="false"
android:layout_weight="4"
android:layout_height="0dp" />
<TimePicker
android:id="@+id/time_picker"
android:layout_weight="4"
android:layout_width="match_parent"
android:layout_height="0dp" />
<Button
android:id="@+id/date_time_set"
android:layout_weight="1"
android:layout_width="match_parent"
android:text="Set"
android:layout_height="0dp" />
</LinearLayout>
代码
final View dialogView = View.inflate(activity, R.layout.date_time_picker, null);
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute());
time = calendar.getTimeInMillis();
alertDialog.dismiss();
}});
alertDialog.setView(dialogView);
alertDialog.show();