YouTube Android API: YouTubePlayerFragment loading spinner

旧城冷巷雨未停 提交于 2019-12-03 13:55:58
Ribesg

I encountered this too, it really looks like a bug. Here is how I managed to work around it.

In your onInitializationSuccess, set a PlaybackEventListener on the player. Override the onBuffering and do something like this:

ViewGroup ytView = (ViewGroup)ytPlayerFragment.getView();
ProgressBar progressBar;
try {
    // As of 2016-02-16, the ProgressBar is at position 0 -> 3 -> 2 in the view tree of the Youtube Player Fragment
    ViewGroup child1 = (ViewGroup)ytView.getChildAt(0);
    ViewGroup child2 = (ViewGroup)child1.getChildAt(3);
    progressBar = (ProgressBar)child2.getChildAt(2);
} catch (Throwable t) {
    // As its position may change, we fallback to looking for it
    progressBar = findProgressBar(ytView);
    // TODO I recommend reporting this problem so that you can update the code in the try branch: direct access is more efficient than searching for it
}

int visibility = isBuffering ? View.VISIBLE : View.INVISIBLE;
if (progressBar != null) {
    progressBar.setVisibility(visibility);
    // Note that you could store the ProgressBar instance somewhere from here, and use that later instead of accessing it again.
}

The findProgressBar method, used as a fallback just in case the YouTube code changes:

private ProgressBar findProgressBar(View view) {
    if (view instanceof ProgressBar) {
        return (ProgressBar)view;
    } else if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup)view;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            ProgressBar res = findProgressBar(viewGroup.getChildAt(i));
            if (res != null) return res;
        }
    }
    return null;
}

This solution works perfectly fine for me, enabling the ProgressBar when the player is buffering and disabling it when it's not.

EDIT: If anyone using this solution discovers that this bug has been fixed or that the position of the ProgressBar has changed, please share so that I can edit my answer, thanks!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!