9

I am using View Pager with fragment to showing image and video, I am able to show image and video properly but I have problem, when I swipe for video, then video is playing, but I swipe next or previous then video is still playing on just next or previous screen but when I move two slide next or previous then video is being stop, but why not on next or previous slide.

I search it more but I did not get any solution, any help will be appreciable. Thanks in advance.

Here is my code:

This is Fragment Class

public class ContentFragment extends Fragment {
    private final String imageResourceId;
    private String type;


    public ContentFragment(String imageResourceId,String type) {
        System.out.println("Path In cons="+imageResourceId+"and type is="+type);
        this.imageResourceId = imageResourceId;
        this.type= type;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("Test", "hello");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.content_layout, container, false);

        TouchImageView imageView = (TouchImageView) view.findViewById(R.id.touchImage);
        imageView.setImageResource(R.id.touchImage);
        imageView.setMaxZoom(10f);
        VideoView videoView =(VideoView) view.findViewById(R.id.videoView1);

        if(type.equals("image")) {
            imageView.invalidate();

            imageView.setVisibility(View.VISIBLE);
            videoView.setVisibility(View.GONE);

            try {
                System.out.println("IN Content Fragment"+imageResourceId.toString());

                Bitmap bmp = BitmapFactory.decodeFile(imageResourceId.toString());
                imageView.setImageBitmap(bmp);

            } catch(Exception e) {
                System.out.println("Error Of image File"+e);
            }


        } else  
        try {
        if(type.equals("video")){
            videoView.invalidate();
            videoView.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);

            String path = imageResourceId.toString();
            videoView.setVideoURI(Uri.parse(path));
                videoView.setMediaController(new MediaController(getActivity()));
                videoView.setFocusable(true);
                videoView.start();
            }
        } catch(Exception e) {
        e.printStackTrace();
        }

        return view;
    }
}

This is pager adapter activity

public class MediaActivity extends FragmentActivity {

     private MyAdapter mAdapter;
        private ViewPager mPager;


       public ArrayList<Content> contentList;
     Context context;
        LinearLayout numberOfPageLayout;
     SharedPreferences sharedPreferences;
     Handler progressHandler;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_media);
            context=(Context) getApplicationContext();                           
                    mPager = (ViewPager) findViewById(R.id.pager);
            progressHandler = new Handler();
            contentList=new ArrayList<Content>();
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        // TODO Auto-generated method stub
                        contentList=new ContentDBAdapter(context).getAllContent();

                        }           
                        return null;
                    }
                    @Override
                    protected void onPostExecute(Void result) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(result);
                        mAdapter = new MyAdapter(getSupportFragmentManager(),contentList);
                        mPager.setAdapter(mAdapter);
                    }
                }.execute();




            mPager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    // TODO Auto-generated method stub


                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });
        }


        public static class MyAdapter extends FragmentPagerAdapter {
            ArrayList <Content>contList=new ArrayList<Content>();
            public MyAdapter(FragmentManager fm,ArrayList<Content> cont) {
                super(fm);
                this.contList=cont;
            }

            @Override
            public int getCount() {
                totalPage=contList.size();
                return contList.size();
            }

            @Override
            public Fragment getItem(int position) {

                Content con=contList.get(position);

                return new ContentFragment(con.getPath(),con.getType());

            }
        }

}
Ankit
  • 191
  • 1
  • 2
  • 8

3 Answers3

14

It is because ViewPager keeps offscreen fragments started. For instance you have a fragment visible to the user. ViewPager will try to keep the previous fragment (on the left side) and the next fragment (on the right side) started. This allows ViewPager performing smooth sliding when user decides to change the page, because the next and the previous pages are already prepared.

In your case the video player is not visible (offscreen), but ViewPager keeps it started as due to the behaviour described above. You can use setOffscreenPageLimit() method to change this behaviour. If you set page limit to 0, then offscreen fragments will be paused immediately. Unfortunately they will not only be paused, but stopped and detached from the activity too. This means when you return back to your fragment, it will recreate the whole layout anew. That's why you can try to override either Fragment.setUserVisibleHint() or Fragment.onHiddenChanged() and execute your pause/play logic there. ViewPager will update hidden state of a fragment depending on whether the fragment is actually visible to user or not.

Hope this helps.

sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86
  • Thanks beworker for your answer, but I resolved this problem in another way just like gallery app in android, I am not using that video view directly, taking it's thumbnail in image view and after click on that thumbnail video will play. but I'll try your solution. – Ankit May 18 '14 at 13:35
9

You have to override setUserVisibleHint method in a fragment where u play video.

public void setUserVisibleHint(boolean isVisibleToUser) {       
    super.setUserVisibleHint(isVisibleToUser);                         
     if (this.isVisible())
     {               
        if (!isVisibleToUser)   // If we are becoming invisible, then...
        {  
          //pause or stop video
        }

        if (isVisibleToUser) 
        {                               
            //play your video               
        }

    }

  }
Manish Butola
  • 557
  • 6
  • 15
  • when i stop / pause player I have Illegal exception and when i use player.release(); it stop the player but cant play for next video or when I return back – Amal Kronz Jul 11 '17 at 12:46
  • I will add my problem as new question ,can take a look for it https://stackoverflow.com/questions/45052603/video-image-viewpager – Amal Kronz Jul 12 '17 at 08:40
0

I handle the problem like this:

boolean isVisible = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {

    isVisible = isVisibleToUser;
        if(player!=null)
            player.pause();       
    super.setUserVisibleHint(isVisibleToUser);
}

then in onCreateView method:

SimpleExoPlayer player;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
    PlayerView playerView = v.findViewById(R.id.playerView);
    playerView.getLayoutParams().width = ListPager.widthPixels;
    playerView.getLayoutParams().height = ListPager.widthPixels;
    if(player!=null)
         player.release();
    player = new SimpleExoPlayer.Builder(App.applicationContext).build();               
    playerView.setPlayer(player);
    MediaItem mediaItem = MediaItem.fromUri(url);
    player.setMediaItem(mediaItem);
    player.prepare();

    //---------The following code is important because if you remove the following if
    // then if the next page is displaying, android will automatically initiate the
    // previous and the next page, and the player will start playing :| 

    if(isVisible)
      player.play();
 }
farhad.kargaran
  • 2,233
  • 1
  • 24
  • 30