Motion Layout OnSwipe отключает клики на YoutubePlayer (API YoutubePlayer)

У меня есть YoutubePlayer, воспроизводящий видео в моем Motion Layout. Я хочу реализовать это youtube-like motion https://developer.android.com/training/constraint-layout/motionlayout/examples#youtube-like_motion

Проблема здесь в том, что в приведенном выше примере они выполняют анимацию с помощью ImageView вместо интерфейса YoutubePlayer. Но, к сожалению, интерфейс проигрывателя YouTube, похоже, «отменяет» прослушиватели кликов и разрешает только клики, а не пролистывания. (это мой вывод).

Интересно, как это реализовано в приложении youtube. Если кто-то может мне ответить, пожалуйста. Мне нужно это в моем приложении.

Я поднял вопрос, пожалуйста, проверьте его. https://issuetracker.google.com/issues/162155197

Это то, что я пробовал:

  1. При настройке touchRegionId на вид, который находится перед проигрывателем YouTube или за ним, клики для интерфейса полностью отключаются. Хотя анимация работает. Я не вижу решения для этого варианта, потому что я думаю, что такое поведение предусмотрено дизайном.

  2. При установке limitBoundsTo для представления оно выполняет свою работу. Он ограничивает область действия OnSwipe такими границами представления. Это работает именно так, как мне нужно ПОКА ИНТЕРФЕЙС ПРОИГРЫВАТЕЛЯ YOUTUBE НЕ ИНИЦИАЛИЗИРОВАН. Сразу после инициализации OnSwipe больше не обнаруживается, и интерфейс только прослушивает щелчки, что позволяет, например, приостановить видео. Если ограничение, связанное с просмотром, больше, чем интерфейс YouTube, я могу провести пальцем по остаткам просмотра. Но интерфейс ютуба не слушает свайпы. Может интерфейс не поддерживает свайпы?

  3. Я пытался установить ничего из вышеперечисленного. Просто OnSwipe с направлением перетаскивания. Свайп работает везде до инициализации ютуба. Когда он инициализируется, пиксели, используемые интерфейсом проигрывателя YouTube, перестают прослушивать свайпы, они прослушивают только клики.

Принимая во внимание 2. и 3., я думаю, что это проблема самого интерфейса. Какое бы предложение у вас ни было, пожалуйста, дайте мне знать. Спасибо.

Это мой макет движения:

<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blackBackground"
    android:nestedScrollingEnabled="false"
    app:layoutDescription="@xml/activity_main_scene"
    app:motionDebug="SHOW_ALL">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/player_background"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:touchscreenBlocksFocus="false"
        android:clickable="false"
        android:background="#000000"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <FrameLayout
        android:id="@+id/main_player"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="@id/player_background"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/player_background" />

</androidx.constraintlayout.motion.widget.MotionLayout>

Это моя активность_main_scene xml

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ConstraintSet android:id="@+id/openYoutubePlayer">
        <Constraint
            android:id="@id/player_background"
            android:layout_width="match_parent"
            android:layout_height="240dp"
            android:elevation="0dp">
            <CustomAttribute
                app:attributeName="backgroundColor"
                app:customColorValue="#000000" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/closeYoutubePlayer">
        <Constraint
            android:id="@id/player_background"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:elevation="4dp">
            <CustomAttribute
                app:attributeName="backgroundColor"
                app:customColorValue="@color/blackBackground" />
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/bottomYoutubePlayer">
        <Constraint
            android:id="@id/main_player"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="@id/player_background"
            app:layout_constraintLeft_toLeftOf="@id/player_background"
            app:layout_constraintTop_toTopOf="@id/player_background" />
        <Constraint
            android:id="@id/player_background"
            android:layout_width="0dp"
            android:layout_height="54dp"
            app:layout_constraintBottom_toTopOf="@id/nav_view"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />
    </ConstraintSet>

    <Transition
        app:constraintSetEnd="@id/openYoutubePlayer"
        app:constraintSetStart="@id/closeYoutubePlayer"
        app:duration="500" />

    <Transition
        android:id="@+id/youtubePlayerIsOpened"
        app:constraintSetEnd="@id/bottomYoutubePlayer"
        app:motionInterpolator="linear"
        app:constraintSetStart="@id/openYoutubePlayer"
        app:duration="500">
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchRegionId="@id/player_background"
            app:touchAnchorId="@id/player_background"/>
    </Transition>

</MotionScene>

РЕДАКТИРОВАНИЕ: ДОБАВЛЕНА ИНИЦИАЛИЗАЦИЯ YOUTUBE

val youtubePlayerSupportFragment = YouTubePlayerSupportFragmentX.newInstance()
            supportFragmentManager.beginTransaction()
                .add(R.id.main_player, youtubePlayerSupportFragment).commit()
            youtubePlayerSupportFragment.initialize(
                resources.getString(R.string.API_KEY),
                object : YouTubePlayer.OnInitializedListener {
                    override fun onInitializationSuccess(
                        p0: YouTubePlayer.Provider?,
                        p1: YouTubePlayer?,
                        p2: Boolean
                    ) {
                        p1?.loadVideo(incomingLink)
                        currentLink = incomingLink
                        youtubePlayer = p1
                    }

                    override fun onInitializationFailure(
                        p0: YouTubePlayer.Provider?,
                        p1: YouTubeInitializationResult?
                    ) {
                        layoutUtils.createToast(
                            applicationContext,
                            "Error al iniciar Youtube"
                        )
                    }
                })

comment
Пожалуйста, покажите код инициализации для проигрывателя YouTube   -  person blind.falcon    schedule 04.08.2020
comment
готово! :) пожалуйста, проверьте это   -  person Lheonair    schedule 04.08.2020
comment
Ок, спасибо. Вы помещаете весь фрагмент проигрывателя YouTube в контейнер main_player. Но если посмотреть на само приложение YouTube, то плеер занимает только часть макета. Попробуйте сделать фрагмент с плеером, вложенным в один макетный контейнер с TextView и кнопками действий. Я думаю, если вы добавите слушателя в такой общий контейнер, все будет работать.   -  person blind.falcon    schedule 04.08.2020
comment
Спасибо за предложение. Первоначально у меня был фрагмент интерфейса проигрывателя YouTube. А в этом фрагменте интерфейс ютуб-плеера использует только часть всего макета. Проблема остается прежней.   -  person Lheonair    schedule 04.08.2020
comment
Как насчет добавления пользовательской обработки касаний к вашему фрагменту youtubeview/youtube? вы можете установить прослушиватель onTouch на любой из них и делать практически все, что хотите. Пробовали ли вы пройти этот путь?   -  person Whitebear    schedule 07.08.2020
comment
Я думал о переопределении onTouch, но у меня еще не было времени его протестировать. Пожалуйста, опубликуйте это как ответ / предложение, чтобы, если это сработает, я мог дать вам награду. В настоящее время нет ответов, и это может сработать.   -  person Lheonair    schedule 07.08.2020


Ответы (1)


Это проблема со сложными сценами макета движения. Чтобы использовать onClick и onSwipe для одного и того же перехода, вам необходимо:

  1. Ручка onSwipe от перехода сцены движения

  2. Обработка onClick из подкласса макета движения

  3. В подклассе MotionLayout (Custom View) переопределите эти 2 метода:

class MyMotionLayout @JvmOverloads constructor(context: Context):MotionLayout(context) {

       override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
           //Check if we have MotionEvent.ACTION_UP while MotionEvent.ACTION_MOVE<0.5
           // i.e ..this was a click
           if(ev==MotionEvent.ACTION_UP){
               return true
           }
           return false
       }
       override fun onTouchEvent(event: MotionEvent): Boolean {
           // Here we actually handle the touch event 
           // This method will only be called if the touch event was intercepted in
           // onInterceptTouchEvent
           callOnClick() 
      
       }
   }
person D Lad    schedule 04.03.2021