I am new on Android Fragments and I want to know that how can I show or implement DatePicker
in simple Fragment
and not a FragmentActivity
.
For example my class name is:
public class FragmentAddCard extends Fragment {
}
Thanks.
In your button click call the DateFragment like this
dob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getFragmentManager(), "DatePicker");
}
});
Here is the code snippet for DateFragment
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@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);
}
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) {
dob.setText(month+"/"+day+"/"+year);
}
}
This is other example:
Calendar cal = Calendar.getInstance(TimeZone.getDefault()); // Get current date
// Create the DatePickerDialog instance
DatePickerDialog datePicker = new DatePickerDialog(this,
R.style.AppBlackTheme, datePickerListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
datePicker.setCancelable(false);
datePicker.setTitle("Select the date");
datePicker.show();
// Listener
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
String year1 = String.valueOf(selectedYear);
String month1 = String.valueOf(selectedMonth + 1);
String day1 = String.valueOf(selectedDay);
TextView tvDt = (TextView) findViewById(R.id.tvDate);
tvDt.setText(day1 + "/" + month1 + "/" + year1);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With