我想在Android活动中嵌入DatePickerDialog
。单击按钮作为对话框时,我不希望显示DatePicker
,而是将其嵌入我的活动本身。我尝试在布局中使用DatePicker
视图,但这似乎与DatePickerDialog
不同。
我正在使用DialogFragment
创建DatePickerDialog
并使用onCreate
MainAcitivity.java
中的以下代码
FragmentTransaction ft = getFragmentManager().beginTransaction();
DatePickerDialogFragment datePickerDialogFragment = DatePickerDialogFragment.newInstance();
ft.add(R.id.main_screen_layout, datePickerDialogFragment); // main_screen_layout is given as the id for the layout related to MainActivity
ft.commit();
// DatePickerDialogFragment.java
public class DatePickerDialogFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerDialogFragment newInstance() {
return new DatePickerDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_datepicker, container, false);
View tv = v.findViewById(R.id.tv);
((TextView)tv).setText("This is a new instance");
return v;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
return new DatePickerDialog(getActivity(), this,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
}
}
如何解决这个问题?
答案 0 :(得分:1)
我在活动布局中有DatePicker和DateTime。我们的想法是允许两者的编辑,组成一个日期时间值,并在用户点击完成/设置按钮后返回它。 下面,您可以找到一些代码,显示DatePicker如何嵌入到布局和活动代码中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<DatePicker
android:id="@+id/date_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:calendarViewShown="false" />
</LinearLayout>
public class DateSelectionActivity extends Activity {
private DatePicker datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
this.datePicker = (DatePicker) this.findViewById(R.id.date_value);
this.datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), null);
// ...
}
private OnClickListener confirmButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// Get user selection
// DateSelectionActivity.this.datePicker.getYear());
// DateSelectionActivity.this.datePicker.getMonth());
// DateSelectionActivity.this.datePicker.getDayOfMonth());
}
}
}