我编写了一个程序,当我在手机上运行该程序时,就会开始播放视频。
现在,视频播放后,如果我将手机旋转到横向模式,我的应用程序也会旋转到横向模式,但视频从头开始播放,这对我来说是个问题。
package com.example.videoview
import android.net.Uri
import android.os.Bundle
import android.widget.MediaController
import androidx.appcompat.app.AppCompatActivity
import com.example.videoview.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var position = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initVideoView()
}
private fun initVideoView() {
val uri = Uri.parse("android.resource://$packageName/${R.raw.paris_video}")
val controller = MediaController(this)
binding.videoView.setMediaController(controller)
binding.videoView.setVideoURI(uri)
binding.videoView.start()
binding.videoView.setOnPreparedListener {
it.setOnVideoSizeChangedListener { _, _, _ ->
controller.setAnchorView(binding.videoView)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("position", binding.videoView.currentPosition)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
position = savedInstanceState.getInt("position")
binding.videoView.seekTo(position)
}
}
我编写了代码,当我将手机旋转到横向模式时,我的应用程序也旋转到横向模式,以便视频不会从一开始就播放,但我不知道为什么它不能正常工作。
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("position", binding.videoView.currentPosition)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
position = savedInstanceState.getInt("position")
binding.videoView.seekTo(position)
}
您对 onSaveInstanceState 和 onRestoreInstanceState 的实现似乎是正确的。
但是,请检查方向改变后是否调用 onRestoreInstanceState。
binding.videoView.setOnPreparedListener {
it.setOnVideoSizeChangedListener { _, _, _ ->
controller.setAnchorView(binding.videoView)
}
// Check if savedInstanceState is not null and contains position
if (savedInstanceState != null && savedInstanceState.containsKey("position")) {
position = savedInstanceState.getInt("position")
binding.videoView.seekTo(position)
}
binding.videoView.start()
}
将 binding.videoView.start() 移至 setOnPreparedListener 内。 检查是否savedInstanceState不为空并且包含该位置,然后在开始视频之前寻找保存的位置。