我刚开始学习 Android 作为一种爱好,我想用两个日期选择器创建一个对话框
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.data_picker_dialog);
dialog.setTitle(R.string.date_period_picker);
dialog.show();
return true;
如何从对话框中获取选定的值?是否有可能在对话框中自动包含确定/取消按钮?
是否有库具有这样的功能(开始和结束日期/期间选择)?
最佳答案
至于实现,您可以有两个按钮:一个显示开始日期的日期选择器,另一个显示结束日期。
编辑:如果您真的想在 1 个对话框中显示 2 个日期选择器,这里有一个如何操作的示例。首先,创建自定义 XML 布局。
/res/layout/custom_date_picker.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<DatePicker
android:id="@+id/dpStartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:calendarViewShown="false" />
<DatePicker
android:id="@+id/dpEndDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:calendarViewShown="false" />
</LinearLayout>
接下来是在对话框中使用上面的布局:
// These variables will hold the date values later
private int startYear, startMonth, startDay, endYear, endMonth, endDay;
/**
* Displays the start and end date picker dialog
*/
public void showDatePicker() {
// Inflate your custom layout containing 2 DatePickers
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
View customView = inflater.inflate(R.layout.custom_date_picker, null);
// Define your date pickers
final DatePicker dpStartDate = (DatePicker) customView.findViewById(R.id.dpStartDate);
final DatePicker dpEndDate = (DatePicker) customView.findViewById(R.id.dpEndDate);
// Build the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(customView); // Set the view of the dialog to your custom layout
builder.setTitle("Select start and end date");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
startYear = dpStartDate.getYear();
startMonth = dpStartDate.getMonth();
startDay = dpStartDate.getDayOfMonth();
endYear = dpEndDate.getYear();
endMonth = dpEndDate.getMonth();
endDay = dpEndDate.getDayOfMonth();
dialog.dismiss();
}});
// Create and show the dialog
builder.create().show();
}
最后,您只需调用 showDatePicker()
即可显示此对话框。
关于android - 如何使用两个日期选择器创建自定义对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691030/