欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用ViewPager加载图片和轮播视频

程序员文章站 2023-11-24 14:05:16
作为android基础组件之一,大家对viewpager已经很熟悉了,网上也有很多使用viewpager来加载图片的案例。但是像微信那样点击图片,可以轮播显示图片和视频的例...

作为android基础组件之一,大家对viewpager已经很熟悉了,网上也有很多使用viewpager来加载图片的案例。但是像微信那样点击图片,可以轮播显示图片和视频的例子却没找到。正巧项目中有需求,可以就花时间写了下,现在给一下核心代码,希望对有此需求的同学们起一个抛砖引玉的作用。话不多说了,上代码:

Android使用ViewPager加载图片和轮播视频

以下是initdata的代码

public void initdata() {
  //把聊天界面的图片和视频找出来,并加到数组中,并在
  //并根据传进来的position来找到视频或图片在数组中的位置
  for (int i = 0; i < msgcount; i++) {
   msg1 msg1 = fridenmessages.messagelist.get(i);
   if (msg1.getmsg().startswith(chatutil.tag_image) || msg1.getmsg().startswith(chatutil.tag_video)) {
    imageurl.add(msg1.getmsg());
    //查看消息postion对应的图片位置
    if (position == i) {
     position = imageurl.size() - 1;
     log.i("tag", "position=" + position);
    }

   }
  }
  log.i("tag", "position=" + position);
  //把要用到的view加到viewlist中
  for (int i = 0; i < imageurl.size(); i++) {
   if (imageurl.get(i).startswith(chatutil.tag_image)) {
    photoview photoview = new photoview(context);
    viewlist.add(photoview);
   } else if (imageurl.get(i).startswith(chatutil.tag_video)) {


    view view1 = layoutinflater.from(context).inflate(r.layout.activity_video_player, null);
    surfacevideoview videoview = (surfacevideoview) view1.findviewbyid(r.id.videoview);
    int screenwidth = getscreenwidth((activity) context);
    int videohight = (int) (screenwidth / (mediarecorderbase.small_video_width / (mediarecorderbase.small_video_height * 1.0f)));
//    int videohight = (int) (screenwidth)*4/3;
    videoview.getlayoutparams().height = videohight;
    videoview.requestlayout();
    view playstatus = view1.findviewbyid(r.id.play_status);
    view loading = view1.findviewbyid(r.id.loading);
    viewlist.add(view1);
   }
  }

  adapter = new myadapter();
  viewpager.setadapter(adapter);
  if (position != -1) {
   viewpager.setcurrentitem(position);
  }
 }
``` public void initevent() {
  //给viewpager设置监听
  viewpager.setonpagechangelistener(new viewpager.onpagechangelistener() {

   @override
   public void onpageselected(int arg0) {

    int childcount = viewpager.getchildcount();//viewpager得到页面的数量
    //如果不是在原页面,让原来页面的视频停止播放
    if(position != arg0){
     position=arg0;
     stopvideo();
    }

    // 遍历当前所有加载过的photoview,恢复所有图片的默认状态

    for (int i = 0; i < childcount; i++) {
     view childat = viewpager.getchildat(i);

     try {
      if (childat != null && childat instanceof photoview) {
       photoview photoview = (photoview) childat;
       photoview.setonphototaplistener(new photoviewattacher.onphototaplistener() {
        @override
        public void onphototap(view view, float x, float y) {
         finish();
        }

        @override
        public void onoutsidephototap() {

        }
       });
      }
     } catch (exception e) {
      e.printstacktrace();
     }
    }
    if (imageurl.get(position).startswith(chatutil.tag_video)) {
     string body = chatapplication.dbhelper.getvideosdpath(imageurl.get(position));
     string url[] = imageurl.get(position).substring(chatutil.tag_video.length()).split("&&");
     view childat = viewlist.get(arg0);
     surfacevideoview videoview = (surfacevideoview) childat.findviewbyid(r.id.videoview);
     mvideoview = videoview;
     mplayerstatus = childat.findviewbyid(r.id.play_status);
     mloading = childat.findviewbyid(r.id.loading);
     log.i("tag", "videourl=" + body);
     setvideourl(body, url);
     //延迟50ms,让播放器播放视频时,让它暂停
     handler handler = new handler();
     handler.postdelayed(new runnable() {
      @override
      public void run() {
       stopvideo();
      }
     }, 50);
    }
   }

   @override
   public void onpagescrolled(int arg0, float arg1, int arg2) {
    // todo auto-generated method stub

   }

   @override
   public void onpagescrollstatechanged(int arg0) {
    // todo auto-generated method stub

   }
  });
 }
 public class myadapter extends pageradapter {

  @override
  public int getcount() {
   return imageurl.size();
  }

  @override
  public view instantiateitem(viewgroup container, int pos) {
   log.i("tag", "pos=" + pos);
   if (imageurl.get(pos).startswith(chatutil.tag_image)) {
    photoview photoview = (photoview) viewlist.get(pos);
    container.addview(photoview, viewgroup.layoutparams.match_parent, viewgroup.layoutparams.match_parent);
    string body[] = imageurl.get(pos).substring(chatutil.tag_image.length()).split("&&");
    log.i("tag", "<image>=" + body[0]);
    imageloader.getinstance().displayimage(body[0], photoview);
    photoview.setscaletype(imageview.scaletype.fit_center);//设置图片显示为充满全屏
    photoview.setonphototaplistener(new photoviewattacher.onphototaplistener() {
     @override
     public void onphototap(view view, float x, float y) {
      finish();
     }

     @override
     public void onoutsidephototap() {

     }
    });
    //   photoview.setonlongclicklistener(longclicklistener);

   } else if (imageurl.get(pos).startswith(chatutil.tag_video)) {
     view view1 = viewlist.get(pos);
    surfacevideoview videoview = (surfacevideoview) view1.findviewbyid(r.id.videoview);
    int screenwidth = getscreenwidth((activity) context);
    int videohight = (int) (screenwidth / (mediarecorderbase.small_video_width / (mediarecorderbase.small_video_height * 1.0f)));
//    int videohight = (int) (screenwidth)*4/3;
    videoview.getlayoutparams().height = videohight;
    videoview.requestlayout();
    view playerstatus = view1.findviewbyid(r.id.play_status);
    view loading = view1.findviewbyid(r.id.loading);
    videoview.setonpreparedlistener(showbigpictureactivity.this);
    videoview.setonplaystatelistener(showbigpictureactivity.this);
    videoview.setonerrorlistener(showbigpictureactivity.this);
    videoview.setonclicklistener(showbigpictureactivity.this);
    videoview.setoninfolistener(showbigpictureactivity.this);
    videoview.setoncompletionlistener(showbigpictureactivity.this);
    container.addview(view1, viewgroup.layoutparams.match_parent, viewgroup.layoutparams.match_parent);

    string body = chatapplication.dbhelper.getvideosdpath(imageurl.get(pos));
    string url[] = imageurl.get(pos).substring(chatutil.tag_video.length()).split("&&");
    //找到是点击聊天界面哪个视频进来的,将局部成员,付给类成员
    if(pos==position) {
     mvideoview = videoview;
     mplayerstatus=playerstatus;
     mloading=loading;
     setvideourl(body,url);

    }



   }

   return viewlist.get(pos);
  }

  @override
  public void destroyitem(viewgroup container, int position, object object) {
   container.removeview((view) object);
  }

  @override
  public boolean isviewfromobject(view view, object object) {
   return view == object;
  }
 }
以下是控制视频播放的接口:
 public void oncompletion(mediaplayer mp) {
  onstatechanged(false);
 }

 @override
 public boolean onerror(mediaplayer mp, int what, int extra) {

  return false;

 }

 @override
 public boolean oninfo(mediaplayer mp, int what, int extra) {
  switch (what) {
   case mediaplayer.media_info_bad_interleaving:
    // 音频和视频数据不正确
    configutil.showshort(context, "视频数据不正确!");
    break;
   case mediaplayer.media_info_buffering_start:
    if (!isfinishing())
     mvideoview.pause();
    break;
   case mediaplayer.media_info_buffering_end:
    if (!isfinishing())
     mvideoview.start();
    break;
   case mediaplayer.media_info_video_rendering_start:
    if (deviceutils.hasjellybean()) {
     mvideoview.setbackground(null);
    } else {
     mvideoview.setbackgrounddrawable(null);
    }
  break;
 }
 return false;
}

 @override
 public void onstatechanged(boolean isplaying) {
  mplayerstatus.setvisibility(isplaying ? view.gone : view.visible);


 }

 @override
 public void onprepared(mediaplayer mp) {
  mvideoview.setvolume(surfacevideoview.getsystemvolumn(this));
  mvideoview.start();
  mloading.setvisibility(view.gone);

 }

我觉得轮播视频的难点在于viewpager只能播放一个视频,而每个viewitem都有继承自surfaceview的surfacevideoview控件, 我让原先页面的surfaceviedeoview停止播放,并把新页面的surfacevideoview付给mvideoview,然后就可以对选中页面的视频进行控制了。

下面来张效果图:

Android使用ViewPager加载图片和轮播视频

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。