Reputation: 13
everytime user select date the TextView only showing current date
public void initOverall(){
TextView dateTest = (TextView)findViewById(R.id.cnvrt);
CalendarView calendarView = (CalendarView)findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String selectedDates = sdf.format(new Date(calendarView.getDate()));
dateTest.setText(selectedDates);
}
});
}
Upvotes: 1
Views: 2744
Reputation: 86306
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
LocalDate date = LocalDate.of(year, Month.values()[month], dayOfMonth);
String selectedDates = date.toString();
dateTest.setText(selectedDates);
}
As has been said in comments, you need to pick up the date that the user has chosen from the arguments passed to onSelectedDayChange
. Unfortunately the month
passed is 0-based, a number in the interval from 0 for January through 11 for December. Month.values()[month]
is my trick for obtaining the correct Month
object. If you prefer, you may instead just add 1:
LocalDate date = LocalDate.of(year, month + 1, dayOfMonth);
I am further exploiting the fact that LocalDate.toString
produces the format you want, so we need no explicit formatter. The format is ISO 8601.
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 0
Reputation: 46
Because you just selected a date but not got it as onSelectedDayChange stage.
And the date you chosen was saved in parameters of onSelectedDayChange.
You can try the following code :
public void initOverall(){
final TextView dateTest = (TextView)findViewById(R.id.cnvrt);
final CalendarView calendarView = (CalendarView)findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String selectedDates = sdf.format(new Date(year-1900,month,dayOfMonth));
dateTest.setText(selectedDates);
}
});
}
Upvotes: 3
Reputation: 845
CalendarView v = new CalendarView( this );
v.setOnDateChangeListener( new CalendarView.OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
this.calendar = new GregorianCalendar( year, month, dayOfMonth );
}//met
});
Upvotes: -1