我只想在Fragment类中创建一个日期和时间选择器。所以我直接将我的片段扩展到Dialog Fragment并覆盖onCreateDialog。所以通过这个我成功创建了一个日期选择器,但我想在日期选择器之后创建一个时间选择器.... 所以我怎么能这样做因为在onCreateDialog中我们无法传递id .. 这是我的代码:
public class DetailsFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener{
Button serviceCenterName;
Dialog dialog; Boolean isvalue;
public DetailsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_booking_details, container, false);
serviceCenterName=(Button)view.findViewById(R.id.serviceCentername);
serviceCenterName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog = onCreateDialog(savedInstanceState);
dialog.show();
}
});
return view;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
/*final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(),this,mHour,mMinute,false);*/
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
public void populateSetDate(int year, int month, int day) {
Log.d("date",month+"/"+day+"/"+year);
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
populateTime(hourOfDay,minute);
}
public void populateTime(int hour, int min) {
Log.d("Time : ",hour+"/"+min);
}
}
答案 0 :(得分:-1)
onClick侦听器中使用日期选择器的代码
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
时间选择器代码
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();