YouTube video and Image in a single ViewPager?

1.8k Views Asked by At

I need to make a slider which could possibly contain a YouTube video, an image, and a gif.

I can make a slider of an image or a gif, but how can I merge them all in single ViewPager. Please help. Any suggestions or links would be helpful.

1

There are 1 best solutions below

1
Rahaf Jawish On

Let's suppose that your fragments will be in fixed positions in your ViewPager.. You should make two Fragments with two different layouts let's call them: ImageFragment and VideoFragment. you should also extend FragmentPagerAdapter and implement getItem(int position) like this:

@Override
public Fragment getItem(int position) {
    if (position == 2)
        return VideoFragment.newInstance();
    return ImageFragment.newInstance();
}

EDIT: So this time we'll suppose that you have many images and one video at the end of the ViewPager.. so you can put the paths of images in ArrayList<String> (maybe local paths or remote paths from server), and put video path in a String variable as well.. and pass each of these strings to the appropriate fragments like this:

    public class MultiMediaAdapter extends FragmentPagerAdapter {
        private List<String> paths;
        private String videoPath;

        public MultiMediaAdapter (FragmentManager fm, List<String> paths, String videoPath) {
            super(fm);
            this.paths = paths;
            this.videoPath = videoPath;
        }

        @Override
        public Fragment getItem(int position) {
//pay attintion that position starts  counting from zero
            if (position == paths.size()) //video at the end of the ViewPager
                return VideoFragment.newInstance(videoPath);
            return ImageFragment.newInstance(paths.get(position));
        }

        @Override
        public int getCount() {
            return this.paths.size()+1; //+1 for the video
        }
    }

and you should load each image in the fragment like this:

 public class ImageFragment extends Fragment {
        private String path;

        public static ImageFragment newInstance(String path){
            ImageFragment fragment = new ImageFragment();
            fragment.setPath(path);

            return fragment;
        }

        private void setPath(String path) {
            this.path = path;
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_image, container, false);

    ImageView imageView = rootView.findViewById(R.id.imageView);

            if (path != null){
              // and here load image into imageView using path, the way you want
            }

            return rootView;
        }
    }

and VideoFragment will be just as similar to ImageFragment