Thursday, 9 May 2019

How to prevent youtube fragment view from reloading when orientation changes

I want to prevent youtube fragment view from reloading when orientation changes in my app. I am using YouTubeAndroidPlayerApi.jar

I am already added android:configChanges="orientation|screenSize", but it is not able to protect reload.

AndroidManifest.xml

<activity android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:configChanges="orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
        </intent-filter>
    </activity>

activity_main.xml

<fragment
    android:id="@+id/youtube_player_fragment"
    android:name="com.google.android.youtube.player.YouTubePlayerFragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String youTubeKey = getString(R.string.YouTubeKey);

        YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_player_fragment);
        youTubePlayerFragment.initialize(youTubeKey, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
    youTubePlayer = player;

    //Enables automatic control of orientation
    youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
    //Show full screen in landscape mode always
    youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
    //System controls will appear automatically
    youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);

    if (!wasRestored) {
        youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
        youTubePlayer.loadVideo(getString(R.string.link));
    }
    else
    {
        youTubePlayer.play();
    }
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
    youTubePlayer = null;
    Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}



from How to prevent youtube fragment view from reloading when orientation changes

No comments:

Post a Comment