Unable to implement custom calendar view library in android java

Viewed 1880

I want to use this Calendar view in my android java app. https://github.com/kizitonwose/CalendarView

I've tried myself first before coming here but I could not implement this in java as documentation is for Kotlin.

Someone please help me, I am stuck on step 2.

Step 2:

Kotlin Code of Documentation:

class DayViewContainer(view: View) : ViewContainer(view) {
    val textView = view.calendarDayText
}

My Java Equivalent Code:

class DayViewContainer extends ViewContainer {

    public DayViewContainer(View view) {
        super(view);
        final TextView calendar_day_text = view.findViewById(R.id.calendarDayText);
    }
}

Kotlin Code of Documentation:

calendarView.dayBinder = object : DayBinder<DayViewContainer> {
    // Called only when a new container is needed.
    override fun create(view: View) = DayViewContainer(view)
    // Called every time we need to reuse a container.
    override fun bind(container: DayViewContainer, day: CalendarDay) {
        container.textView.text = day.date.dayOfMonth.toString()
    }
}

My Java Equivalent Code:

calendarView.setDayBinder(new DayBinder<DayViewContainer>(){

    @Override
        public DayViewContainer create(View view) {
        return new DayViewContainer(view);
    }

    @Override
    public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
        TextView textView = 
         dayViewContainer.getView().findViewById(R.id.calendarDayText);
        textView.setText(calendarDay.getDate().getDayOfMonth());
    }
});
2 Answers

DayViewContainer should make the TextView a member variable so you can actually access it. You could make a getter for it, but for simple classes like this my personal preference is to make fields public final to simplify it.

class DayViewContainer extends ViewContainer {

    public final TextView calendarDayText;

    public DayViewContainer(View view) {
        super(view);
        calendarDayText = view.findViewById(R.id.calendarDayText);
    }
}

And since you're calling your own Java code, and we made this member field public, you don't need to call a getter for it in your DayBinder:

@Override
public void bind(DayViewContainer dayViewContainer, CalendarDay calendarDay) {
    dayViewContainer.calendarDayText.setText(calendarDay.getDate().getDayOfMonth());
}

Thank you guys for showing some concern here.

I figured it out.

The mistake was that I was not converting integer days to String to use it as text on TextView. The correction is here in following line:

textView.setText(Integer.toString(calendarDay.getDate().getDayOfMonth()));
Related