Android : YouTube Android fragment flickering

on Friday, August 15, 2014


I'm embedding Youtube videos in my Android app using the official SDK. Problem is, the screen gets flickered(black color background for <0.5 seconds) each time a video is initialized.


XML:



<LinearLayout
android:id="@+id/youTube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/cardui"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:visibility="visible"
tools:visibility="visible">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="5dp"
android:fontFamily="sans-serif-light"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:text="Watch video"
android:textAppearance="?android:attr/textAppearanceLarge" />

<!-- This is where Youtube fragment will be added -->

</LinearLayout>


Youtube Fragment Code:



public static class PlayerYouTubeFrag extends YouTubePlayerSupportFragment {

private String videoId;

public static PlayerYouTubeFrag newInstance(String videoId) {

PlayerYouTubeFrag playerYouTubeFrag = new PlayerYouTubeFrag();

Bundle bundle = new Bundle();
bundle.putString("videoId", videoId);
playerYouTubeFrag.setArguments(bundle);

return playerYouTubeFrag;
}

@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
init();

return super.onCreateView(layoutInflater, viewGroup, bundle);
}

private void init() {
videoId = getArguments().getString("videoId");
initialize(youtubeKey, new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youtubePlayer = youTubePlayer;
youtubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
@Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});

if (!b) {
youtubePlayer.cueVideo(videoId);
youtubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
}
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "Player initialization failed");
}
});
}
}


And finally, adding the Fragment to layout:



mYoutubePlayerFragment = PlayerYouTubeFrag.newInstance(videoId);
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).add(R.id.youTube, mYoutubePlayerFragment).commit();
(findViewById(R.id.youTube)).setVisibility(View.VISIBLE);

0 comments:

Post a Comment