视频未在片段ViewPager中暂停

时间:2014-01-23 07:16:57

标签: android imageview android-viewpager fragment android-videoview

我正在使用带有片段的View Pager来显示图像和视频,我能够正确显示图像和视频但我有问题,当我滑动视频,然后视频正在播放,但我在下一次或之前滑动然后视频是仍然只在下一个或上一个屏幕上播放但是当我下一个或上一个移动两张幻灯片时,视频正在停止,但为什么不在下一张或上一张幻灯片上播放。

我搜索的更多,但我没有得到任何解决方案,任何帮助都会很明显。 提前谢谢。

这是我的代码:

这是片段类

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;
    }
}

这是寻呼机适配器活动

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());

            }
        }

}

3 个答案:

答案 0 :(得分:10)

这是因为ViewPager启动了屏幕外片段。例如,您有一个可供用户看到的片段。 ViewPager将尝试保留前一个片段(在左侧)和下一个片段(在右侧)开始。当用户决定更改页面时,这允许ViewPager执行平滑滑动,因为已经准备好了下一页和前一页。

在您的情况下,视频播放器不可见(屏幕外),但由于上述行为,ViewPager会使其保持启动状态。您可以使用setOffscreenPageLimit()方法更改此行为。如果您将页面限制设置为0,则会立即暂停屏幕外片段。不幸的是,它们不仅会被暂停,而且会停止并脱离活动。这意味着当您返回到片段时,它将重新创建整个布局。这就是为什么您可以尝试覆盖Fragment.setUserVisibleHint()Fragment.onHiddenChanged()并在那里执行暂停/播放逻辑的原因。 ViewPager将根据片段是否实际对用户可见而更新片段的隐藏状态。

希望这有帮助。

答案 1 :(得分:5)

你必须在你播放视频的片段中覆盖setUserVisibleHint方法。

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               
        }

    }

  }

答案 2 :(得分:0)

我这样处理问题:

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

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

然后使用onCreateView方法:

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();
 }