Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Youtube video within viewpager

I want to set YouTube videos within ViewPager. For this I have set FrameLayout in adapter and I have set YoutubeVideoFragment in it like below:

My Adapter for ViewPager:

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import np.com.test.R;
import np.com.test.fragment.YoutubeVideoFragment;

/**
 * Created by Vikash on 8/18/2015.
 */
public class TutorialVideoAdapter extends PagerAdapter {
private List<String> mList;
private Activity mActivity;

public TutorialVideoAdapter(Activity activity, List<String> list) {
    mActivity = activity;
    mList = list;
}

@Override
public int getCount() {
    return mList.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

    LayoutInflater inflater = (LayoutInflater) mActivity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.pager_video_tutorial, container, false);

    YoutubeVideoFragment fragment = new YoutubeVideoFragment();
    Bundle bundle = new Bundle();
    bundle.putString("video_key", mList.get(position));
    fragment.setArguments(bundle);

    FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_container, fragment);
    transaction.commit();

    container.addView(view);
    return view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
}
}

In above adapter in which YoutubeVideoFragment is use to load Youtube video.

YoutubeVideoFragment:

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;

import np.com.test.R;
import np.com.test.utils.Config;

/**
 * Created by Vikash on 8/18/2015.
 */
public class YoutubeVideoFragment extends Fragment implements YouTubePlayer.OnInitializedListener {

    private String YOUTUBE_VIDEO_CODE;
    private static final int RECOVERY_DIALOG_REQUEST = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        YOUTUBE_VIDEO_CODE = getArguments().getString("video_key");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View fragmentYoutubeView = inflater.inflate(R.layout.fragment_youtube_video, container, false);
        YouTubePlayerFragment mYoutubePlayerFragment = new YouTubePlayerFragment();
        mYoutubePlayerFragment.initialize(Config.GOOGLE_API_KEY, this);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_youtube_player, mYoutubePlayerFragment);
        fragmentTransaction.commit();

        return fragmentYoutubeView;
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            player.cueVideo(YOUTUBE_VIDEO_CODE);
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
        } else {
            String errorMessage = String.format(
                    getString(R.string.error_player), errorReason.toString());
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
        }
    }
}

XML layout code for both fragmenet_youtube_videoandpager_video_tutorial:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_youtube_player"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

What i got? Only showing first position fragment. I can see only one video in viewpager remaining page are are blank.

What i tried? I tried to search for the solution from yesterday in Google but couldn't get success.

My Problem: How to load remaining YoutubeVideoFragment?

Thank you.

like image 455
Vikash Parajuli Avatar asked Aug 19 '15 05:08

Vikash Parajuli


People also ask

How do I add a viewpager to an existing layout?

Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. An adapter populates the pages inside the Viewpager.

How do I add a pager to an XML file?

Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. An adapter populates the pages inside the Viewpager. PagerAdapter is the base class which is extended by FragmentPagerAdapter and FragmentStatePagerAdapter.

How to display YouTube videos inside your app without redirecting to YouTube?

If you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of video id inside your app itself without redirecting your user to YouTube.

How to integrate YouTube video player in Android app?

implementation ‘com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3’ Now click on the “sync now” option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating YouTube video player into the app. Now change the project tab in the top left corner to Android.


2 Answers

I got the error that the YouTube view is overlayed by my view pager when the pager contains multiple YouTubePlayerFragments.

After a lot of research, I solved it as follows.

  • Override setUserVisibleHint() of the fragment.

  • Release the previous YouTubePlayer (mYoutubePlayer).

  • Create a new instance of the player by initialize().

  • In onInitilizationSuccess, load the player with the youtube_video_id.

Note: I am using FragmentStatePagerAdapter.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (!isVisibleToUser && mYoutubePlayer != null) {
        mYoutubePlayer.release();
    }
    if (isVisibleToUser && mYouTubePlayerSupportFragment != null) {
        mYouTubePlayerSupportFragment.initialize(API_KEY, Context);
    }
like image 125
Ram Prakash Bhat Avatar answered Oct 19 '22 19:10

Ram Prakash Bhat


Inspired by the answer above, I have a working solution for this problem.

In OnCreate():

mYouTubePlayerSupportFragment = YouTubePlayerSupportFragment.newInstance();
    if (getUserVisibleHint()) {
        Log.v (TAG, "Committing transaction, URL : " + getArguments().getString(KeyConstant.KEY_VIDEO_URL));
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.fl_youtube_player, mYouTubePlayerSupportFragment).commit();
        mYouTubePlayerSupportFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
    }

In setUserVisibleHint():

if (!isVisibleToUser && mYoutubePlayer != null) {
    Log.v (TAG, "Releasing youtube player, URL : " + getArguments().getString(KeyConstant.KEY_VIDEO_URL));
    mYoutubePlayer.release();
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.remove(mYouTubePlayerSupportFragment).commit();
}
if (isVisibleToUser && mYouTubePlayerSupportFragment != null) {
    Log.v (TAG, "Initializing youtube player, URL : " + getArguments().getString(KeyConstant.KEY_VIDEO_URL));
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.replace(R.id.fl_youtube_player, mYouTubePlayerSupportFragment).commit();
    mYouTubePlayerSupportFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
like image 41
gaurav jain Avatar answered Oct 19 '22 19:10

gaurav jain