Xamarin-Java库侦听器和事件?

时间:2019-02-27 19:04:03

标签: android xamarin xamarin-binding

我正在尝试访问此Android library with Xamarin bindings(原始的here)中用户定义的侦听器,以了解日历何时滚动到另一个月份或在日历上选择了日期。

示例中给出的代码中的侦听器如下:

        compactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
        @Override
        public void onDayClick(Date dateClicked) {
            List<Event> events = compactCalendarView.getEvents(dateClicked);
            Log.d(TAG, "Day was clicked: " + dateClicked + " with events " + events);
        }

        @Override
        public void onMonthScroll(Date firstDayOfNewMonth) {
            Log.d(TAG, "Month was scrolled to: " + firstDayOfNewMonth);
        }
    });

我要访问的是onDayClick侦听器。它在Java的Controller类中的代码并未指定按钮,而是计算了单击日期的日历中的位置,然后根据该计算返回日期。

    void onSingleTapUp(MotionEvent e) {

    // Don't handle single tap when calendar is scrolling and is not stationary

    if (isScrolling()) {

        return;

    }



    int dayColumn = Math.round((paddingLeft + e.getX() - paddingWidth - paddingRight) / widthPerDay);

    int dayRow = Math.round((e.getY() - paddingHeight) / heightPerDay);



    setCalenderToFirstDayOfMonth(calendarWithFirstDayOfMonth, currentDate, monthsScrolledSoFar(), 0);



    int firstDayOfMonth = getDayOfWeek(calendarWithFirstDayOfMonth);



    int dayOfMonth = ((dayRow - 1) * 7) - firstDayOfMonth;

    if (isRtl) {

        dayOfMonth +=  6 - dayColumn;

    } else {

        dayOfMonth += dayColumn;

    }

    if (dayOfMonth < calendarWithFirstDayOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH)

            && dayOfMonth >= 0) {

        calendarWithFirstDayOfMonth.add(Calendar.DATE, dayOfMonth);



        currentCalender.setTimeInMillis(calendarWithFirstDayOfMonth.getTimeInMillis());

        performOnDayClickCallback(currentCalender.getTime());

    }

}

尝试将侦听器声明为CompactCalendarView.ICompactCalendarViewListener listener;似乎很好,但是尝试为其分配新的CompactCalendarViewListener()会给我一个“未定义的函数”错误。

我了解C#使用事件而不是侦听器,但是我不知道它如何处理Java库中用户定义的侦听器,或者如何覆盖onDayClick / onMonthScroll之类的事件。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您在Xamarin.Android中使用C#的类不能是匿名的,因为C#不支持匿名声明,您需要做的事情是这样的:

compactCalendarView.SetListener(new CompactCalendarViewListener());

然后为Android的Dispose方法和您要使用类似以下内容的接口定义一个从Java.Lang.Object继承的类:

 public class CompactCalendarViewListener : Java.Lang.Object, CompactCalendarView.ICompactCalendarViewListener
{
    public void OnDayClick(Date p0)
    {
        // throw new System.NotImplementedException();
    }

    public void OnMonthScroll(Date p0)
    {
        //throw new System.NotImplementedException();
    }
}