要实现使用ExoPlayer和SurfaceView在Android Kotlin中播放视频,并且能够在嵌套的ConstraintLayout和NestedScrollView中进行横竖屏切换效果,可以按照以下步骤进行操作:

  1. 在build.gradle文件中添加ExoPlayer的依赖项:
implementation 'com.google.android.exoplayer:exoplayer:2.X.X'

(请将2.X.X替换为最新版本号)

  1. 在布局文件中,使用ConstraintLayout和NestedScrollView包裹SurfaceView,并添加一个切换横竖屏按钮:
<androidx.constraintlayout.widget.ConstraintLayout
    ...>
    
    <androidx.core.widget.NestedScrollView
        ...>
        
        <SurfaceView
            android:id="@+id/surfaceView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </androidx.core.widget.NestedScrollView>
    
    <Button
        android:id="@+id/fullscreenButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fullscreen"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  1. 在Activity或Fragment中,初始化ExoPlayer并将SurfaceView设置为其渲染器:
private lateinit var player: SimpleExoPlayer

override fun onCreate(savedInstanceState: Bundle?) {
    ...

    val surfaceView = findViewById<SurfaceView>(R.id.surfaceView)
    surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
        override fun surfaceCreated(holder: SurfaceHolder) {
            player.setVideoSurface(holder.surface)
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            player.setVideoSurface(null)
        }
    })
    
    player = ExoPlayerFactory.newSimpleInstance(this)
    // 设置ExoPlayer的其他配置,如媒体源等
    
    ...
}
  1. 在切换横竖屏按钮的点击事件中,切换Activity或Fragment的屏幕方向:
val fullscreenButton = findViewById<Button>(R.id.fullscreenButton)
fullscreenButton.setOnClickListener {
    requestedOrientation = if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    } else {
        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }
}
  1. 在Manifest文件中,为该Activity或Fragment添加android:configChanges="orientation"属性,以在切换屏幕方向时保持Activity或Fragment的状态:
<activity
    android:name=".YourActivity"
    android:configChanges="orientation" />

通过以上步骤,你就可以在Android Kotlin中使用ExoPlayer和SurfaceView来播放视频,并且在嵌套的ConstraintLayout和NestedScrollView中实现横竖屏切换效果了

Android kotlin使用ExoPlayer+SurfaceView NestedScrollView嵌套ConstraintLayout +SurfaceView SurfaceView在中间 播放视频 横竖屏切换效果

原文地址: https://www.cveoy.top/t/topic/iIaD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录