如何处理YouTube片段OnSaveInstanceState

时间:2018-09-24 14:39:02

标签: android android-fragments youtube-api android-youtube-api

问题

YouTube文档并未明确概述在其API guidedocumentation(适用于Android)的YouTube生命周期中调用Dim wbkHelper as Workbook Set wbkHelper = Workbooks.Open(filePath, ReadOnly:=true) Set wbkHelper = Workbooks(filename) ' note filename needs to be filepath without the path 的位置。

为确保YouTube播放器从屏幕旋转seekToMillis()时左边的位置开始起步,但是,此方法无法按预期在seekToMillis(...)loadVideo(...)之前或之后直接调用。

预期

呼叫play()以在毫秒中的特定时间点开始播放视频。

1 个答案:

答案 0 :(得分:0)

解决方案

在{strong> YouTubePlayer.PlayerStateChangeListener 中发生事件后,seekToMillis(...)方法将起作用。因此,可以将保存的实例状态束传递到为PlayerStateChangeListener创建的内部类中。

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = FragmentYoutubeDialogBinding.inflate(inflater, container, false)

    val youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance()

    youTubePlayerFragment.initialize(Auth.APP_API_ID, object : OnInitializedListener {

        override fun onInitializationSuccess(provider: Provider, player: YouTubePlayer, wasRestored: Boolean) {
            if (!wasRestored) {
                youtubePlayer = player
                player.setPlayerStateChangeListener(MyPlayerStateChangeListener(savedInstanceState))
                player.setPlaybackEventListener(MyPlaybackEventListener())
                player.loadVideo(arguments!!.getString(ITEM_ID))
                player.play()
            }
        }

        override fun onInitializationFailure(provider: Provider, result: YouTubeInitializationResult) {
            // TODO: add log statement.
        }
    })
    childFragmentManager.beginTransaction().replace(R.id.youtubePlayer, youTubePlayerFragment as Fragment).commit()

    return binding.root
}


private inner class MyPlayerStateChangeListener(var savedInstanceState: Bundle?) : YouTubePlayer.PlayerStateChangeListener {
    internal var playerState = "UNINITIALIZED"

    override fun onLoading() {
        playerState = "LOADING"
    }

    override fun onLoaded(videoId: String) {
        playerState = String.format("LOADED %s", videoId)
    }

    override fun onAdStarted() {
        playerState = "AD_STARTED"
    }

    override fun onVideoStarted() {
        if (savedInstanceState != null) {
            println("YT_CURRENT: " + savedInstanceState!!.getInt(YOUTUBE_CURRENT_TIME_KEY))
            youtubePlayer.seekToMillis(savedInstanceState!!.getInt(YOUTUBE_CURRENT_TIME_KEY))
            playerState = "VIDEO_STARTED"
        }
    }