片段中的代码:
public class DatepickerFragment extends Fragment {
TextView etDate;
static final int DATE_ID = 0;
Calendar C = Calendar.getInstance();
private int mYearIni, mMonthIni, mDayIni, sYearIni, sMonthIni, sDayIni;
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
mYearIni = year;
mMonthIni = month;
mDayIni = dayOfMonth;
etDate.setText(mDayIni + "-" + (mMonthIni + 1) + "-" + mYearIni + " ");
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_ID:
return new DatePickerDialog(getContext(), mDateSetListener, sYearIni, sMonthIni, sDayIni);
}
return null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_datepicker, container, false);
etDate= rootView.findViewById(R.id.etDate);
sMonthIni = C.get(Calendar.MONTH);
sDayIni = C.get(Calendar.DAY_OF_MONTH);
sYearIni = C.get(Calendar.YEAR);
etDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().showDialog(DATE_ID);
}
});
return rootView;
}
我正在尝试使用此代码进行活动然后成功,但我尝试使用Fragment datepicker没有显示。我的片段在滑块viewpager中,我尝试使用片段对话框,并且viewpager适配器是错误的。
如何在Fragment中显示DatePicker?
答案 0 :(得分:0)
使您的片段实现为DatePickerDialog.OnDateSetListener
为当前日期创建日历实例
创建DatePicker对话框并显示
public class YourFragment extends Fragment implements android.app.DatePickerDialog.OnDateSetListener {
/**
* Create new fragment.
*/
public static YourFragment ofNew() {
YourFragment fragment = new YourFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.layout_fragment, container, false);
Button button = rootView.findViewById(R.id.show);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAndroidPicker();
}
;
});
return rootView;
}
private void showAndroidPicker() {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
this, year, month, day);
datePickerDialog.show();
}
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
}
}