Не удается изменить Android CalendarView на другой месяц (Samsung S Duos — Android 4.2.2)

Android представил CalendarView еще в API 11. Я реализовал его в своем приложении, и, похоже, оно работает нормально в том смысле, что оно отображает совершенно обычный календарь на целый месяц, и я могу выбрать дату. Он запускает соответствующее событие, и я могу без проблем прочитать выбранную дату в своем коде.

снимок экрана моего CalendarView

Но я не могу продвинуть его из текущего месяца! В документации говорится

Пользователь может выбрать дату, нажав на нее, и может прокручивать календарь до нужной даты.

(«запись» появляется в документации; я предполагаю, что это опечатка для «выстукивания»)

Я пробовал швырять, пролистывать, прокручивать, и ничего не происходит. Есть ли что-то, что мне нужно сделать, чтобы включить эту функцию?

Мой XML выглядит так:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- This linear layout is because the scrollview can have only 1 direct child -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <!-- Relative layout for Workorder -->
        <RelativeLayout
            android:id="@+id/rellayWorkorder"
            android:background="#383838"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/workorderlabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Work Order:"/>

            <TextView
                android:id="@+id/workorderContent"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_margin="2dp"
                android:gravity="right"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="---workorder---"/>
        </RelativeLayout>


        <!-- Relative layout for Required Time
   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"></FrameLayout> -->

        <RelativeLayout
            android:id="@+id/rellayRequiredTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/requiredTimelabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Required Time:"/>

            <TextView
                android:id="@+id/requiredTimeContent"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_margin="2dp"
                android:gravity="right"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="--- 00 minutes ---"/>
        </RelativeLayout>

        <!-- Relative layout for Time remaining -->
        <RelativeLayout
            android:id="@+id/rellayTimeRemaining"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/timeremaininglabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Time Remaining:"/>

            <TextView
                android:id="@+id/tviewtimeremainingContent"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_margin="2dp"
                android:gravity="right"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="--- 0:00:00---"/>
        </RelativeLayout>

        <!--  Linear layout for Record Start / Record End buttons -->
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"  >
            <Button
                android:id="@+id/debulkrecordStart"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:layout_marginRight="4dp"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:onClick="OnSetRecordStartTimeClick"
                android:text="Record Start"/>
            <Button
                android:id="@+id/debulkrecordEnd"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:layout_marginRight="4dp"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:onClick="OnSetRecordEndTimeClick"
                android:text="Record End"/>
        </LinearLayout>

        <!-- Relative layout for Vacuum level -->
        <RelativeLayout
            android:id="@+id/rellayvacuumlevel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/vaclabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Vacuum Level (inches Hg):"/>
            <EditText
                android:id="@+id/vacleveledit"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight = "true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:inputType="text|textCapCharacters"
                android:text="vac level"
                android:layout_marginRight="2dp"
                android:layout_marginTop="2dp"
                android:layout_marginBottom="2dp"/>
        </RelativeLayout>

        <!-- Relative layout for Vac Gauge Equipment # -->
        <RelativeLayout
            android:id="@+id/rlayvacuumGauge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/vacgaugelabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Vac Gauge Equipment #:"/>
            <EditText
                android:id="@+id/vacgaugeedit"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight = "true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:inputType="text|textCapCharacters"
                android:text="equip. #"/>
        </RelativeLayout>



        <!-- Relative layout for Calibration Due date -->
        <RelativeLayout
            android:id="@+id/rlaycalibdue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp">
            <TextView
                android:id="@+id/calibduelabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Calibration Due Date:"/>
            <EditText
                android:id="@+id/calibdueedit"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight = "true"
                android:layout_margin="2dp"
                android:gravity="left"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:inputType="text|textCapCharacters"
                android:text="mm/dd/yyyy"/>
        </RelativeLayout>


        <CalendarView
            android:id="@+id/debulkcalendar"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            android:minDate="01/01/2016"
            android:maxDate="11/30/2016"
            />


        <!--  this linear layout is for the debulk override and done buttons  -->
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"  >
            <Button
                android:id="@+id/debulkOverride"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:layout_marginRight="4dp"
                android:onClick="OnResetClick"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Override"/>
            <Button
                android:id="@+id/debulkDone"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="6dp"
                android:layout_marginRight="2dp"
                android:onClick="onDoneBtnClick"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Done"/>
        </LinearLayout>

    </LinearLayout>

</ScrollView>

Правки:
Извините за длинный XML - в моем исходном сообщении у меня был только CalendarView, но кто-то запросил весь XML.

Также, чтобы исключить возможность того, что это может быть уникально для устройства, я протестировал это на своем Samsung S5 (Android 5.0) и получил те же результаты.


person user316117    schedule 09.06.2016    source источник
comment
@Artur Gniewowski - нет, это не имеет к этому никакого отношения. Этот вопрос касается генерации и обработки событий в коде программной части. Мой вопрос касается поведения пользовательского интерфейса.   -  person user316117    schedule 11.06.2016
comment
Это специально для (Samsung S Duos — Android 4.2.2)? Вы пробовали на других устройствах?   -  person mgcaguioa    schedule 14.06.2016
comment
Можете ли вы опубликовать весь XML-макет?   -  person mgcaguioa    schedule 14.06.2016
comment
@mgcaguioa Да, я также попробовал это на S5 под управлением Android 5.0 и получил те же результаты. (Отредактировал мой пост, чтобы отразить это) Кроме того, я принял ваше предложение и опубликовал весь XML - изначально я этого не делал, потому что, как вы видите, он огромен.   -  person user316117    schedule 14.06.2016


Ответы (2)


согласно моему предположению, это не прокрутка или прокрутка только из-за прокручиваемого родителя, можете ли вы проверить это без просмотра прокрутки?

потому что я тестировал его с

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
    <CalendarView
    android:id="@+id/debulkcalendar"
    android:layout_width="match_parent"
    android:layout_height="240dp"
    android:minDate="01/01/2016"
    android:maxDate="11/30/2016"/>
</LinearLayout>

и работает отлично

вы можете использовать NestedScrollView

NestedScrollView похож на ScrollView, но поддерживает работу как родителя с вложенной прокруткой, так и дочернего элемента как в новой, так и в старой версии Android. Вложенная прокрутка включена по умолчанию.

person RBK    schedule 14.06.2016

@RBK был прав, ваш parentView(ScrollView) мешает его childView(CalendarView), что делает ваш CalendarView непрокручиваемым. Однако вы можете создать свой собственный CalendarView, который расширяет базовый класс CalendarView и переопределяет метод onInterceptTouchEvent, чтобы получить то, что вы хотите.

Создайте свой собственный класс CalendarView:

public class CalendarViewScrollable extends CalendarView {

    public CalendarViewScrollable(Context context) {
        super(context);
    }

    public CalendarViewScrollable(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CalendarViewScrollable(Context context, AttributeSet attrs,
                              int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
            ViewParent p = getParent();
            if (p != null)
                p.requestDisallowInterceptTouchEvent(true);
        }
        return false;
    }
}

Используйте его в файле макета XML:

<com.example.app.views.CalendarViewScrollable
 android:id="@+id/debulkcalendar"
 android:layout_width="match_parent"
 android:layout_height="240dp"
 android:minDate="01/01/2016"
 android:maxDate="11/30/2016" />

Ссылка из этого оригинального ответа

person mgcaguioa    schedule 15.06.2016
comment
Я думаю, что лучше использовать встроенный класс, такой как NestedScrollView, вместо того, чтобы настраивать какой-либо класс. - person RBK; 15.06.2016