video & image viewPager

耗尽温柔 提交于 2019-12-23 02:22:40

问题


I have a problem in my code can anyone help me?

I need to make app play story like Messenger app
I want to display a list of images and videos in viewpager automatically or manually

I do it but I faced some problem

First:

when page of image is view and the next page play video the sound of video is playing when view the image because the pager load the next fragment i used mViewPager.setOffscreenPageLimit(0); but i didn't do any thing

Second one:

when I move manually from video to image the video not stop playing when I search for a solution I found this:

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

it's stop the player but if there is a video in next page it doesn't play How can I solve this problem?

My code:

    public class PostsViews extends Activity {
ArrayList<Post> postsList;
Post postView;
Debate debate;
int position;
private ViewPager mViewPager;
private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
private Timer t = new Timer();
private int mCurrentPagerIndex = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_posts_views);
    position = 0;

    ArrayList postList = new ArrayList<>();
    postList.add(new Post("debate_112254", "post_123", 1, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FImages%2FPhoto_96uMAYBw8b.jpg?alt=media&token=71a5fb9d-7a71-465b-b4e3-4ad2c7513bc5"));
    postList.add(new Post("debate_112254", "post_111", 2, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FVideo%2FVideo_ZVZFgP5JGT.mp4?alt=media&token=07ecb08f-950b-46e3-86aa-ea72e6ccf8d5"));
    postList.add(new Post("debate_112254", "post_1563", 2, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FImages%2FPhoto_mWB8XRF7m5.jpg?alt=media&token=85ca502a-09df-46ab-9b0f-218e28487513"));
    postList.add(new Post("debate_112254", "post_189", 1, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FImages%2FPhoto_qVxVgeqUmR.jpg?alt=media&token=8c079e15-4579-41ee-b373-f34dc23ad045"));
    postList.add(new Post("debate_112254", "post_561", 1, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FImages%2FPhoto_L4wKupgboV.jpg?alt=media&token=3f523167-426c-43bd-91df-b146ee8633db"));
    postList.add(new Post("debate_112254", "post_56221", 2, "https://firebasestorage.googleapis.com/v0/b/satol-19f92.appspot.com/o/UsersPost%2FVideo%2FVideo_qS6dMVjMv0.mp4?alt=media&token=fca08c17-b4bb-46eb-a698-eef1f3df3980"));
    debate = new Debate("debate_112254", postList, "2017-07-12 12:30");
    postsList = debate.getPost();
    Log.i("-----", debate.getKey());
    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getFragmentManager(), debate);
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
    mViewPager.setCurrentItem(position);
    mViewPager.setOffscreenPageLimit(0);
    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            t.cancel();
            t = new Timer();
            snapImage();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    snapImage();
}

public void snapImage() {
    final int pos;
    pos = mViewPager.getCurrentItem();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (debate.getPost().get(mViewPager.getCurrentItem()).getPostType() == 1) {
                if (pos == debate.getPost().size() - 1) {
                    try {
                        t.cancel();
                        finish();
                    } catch (Exception e) {
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mViewPager.setCurrentItem(pos + 1);
                        }
                    });
                }
            }
        }
    }, 10000, 10000);


}

@Override
public void onPause() {
    super.onPause();
    try {
        if (t != null)
            t.cancel();
    } catch (Exception e) {
    }
}

}

    public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
Depate depate;
public DemoCollectionPagerAdapter(FragmentManager fm, Depate depate) {
    super(fm);
    this.depate=depate;

}

@Override
public Fragment getItem(int i) {
    Fragment fragment = new DemoObjectFragment();
    Bundle args = new Bundle();
    // Our object is just an integer :-P
    args.putInt(DemoObjectFragment.ARG_OBJECT, i );
    args.putSerializable("depate",depate);
    fragment.setArguments(args);
    return fragment;
}

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

@Override
public CharSequence getPageTitle(int position) {
    return "OBJECT " + (position + 1);
}
}


DemoObjectFragment.class
      public class DemoObjectFragment extends Fragment implements SurfaceHolder.Callback,
    MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener {

public static final String ARG_OBJECT = "object";
private Depate depate;
private int position;

SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private ImageView postImage;

private Post postView;
private String filePath;
private String type;

private FrameLayout frameLayout;
private RelativeLayout rl_video;
private RelativeLayout activity_view_post;
private int mVideoWidth, mVideoHeight;

private Activity activity;

private String fileName;
private ProgressBar loading;

private LinearLayout ll_data;
private ImageView thumb;

private long POST_VIEW_COUNT = 1;
private String depateID;
private String postID;
long time;
private ProgressDialog pd;
private ArrayList<String> debateList = new ArrayList<>();

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

    View viewLayout = inflater.inflate(R.layout.fragment_demo_object, container, false);
    Bundle args = getArguments();
    depate = (Depate) (args.getSerializable("depate"));
    position = args.getInt(ARG_OBJECT);
    postView = depate.getPost().get(position);
    activity = getActivity();


    frameLayout = (FrameLayout) viewLayout.findViewById(R.id.videoSurfaceContainer);

    rl_video = (RelativeLayout) viewLayout.findViewById(R.id.rl_video);
    postImage = (ImageView) viewLayout.findViewById(R.id.postImage);
    thumb = (ImageView) viewLayout.findViewById(R.id.thumb);


    ll_data = (LinearLayout) viewLayout.findViewById(R.id.ll_data);
    loading = (ProgressBar) viewLayout.findViewById(R.id.loading);
    loading.getIndeterminateDrawable().setColorFilter(Color.parseColor("#6782fa"), android.graphics.PorterDuff.Mode.MULTIPLY);
    loading.setVisibility(View.VISIBLE);
    videoSurface = (SurfaceView) viewLayout.findViewById(R.id.videoSurface);


    fillData(postView, depate);

    return viewLayout;
}


private void fillData(final Post postView, Depate depate) {
    filePath = postView.getFilePath();
    type = (postView.getPostType() == 1 ? "image/jpeg" : "video/mp4");

    if (type.equalsIgnoreCase("video/mp4")) {
        SurfaceHolder videoHolder = videoSurface.getHolder();
        videoHolder.addCallback(this);
        player = new MediaPlayer();
        try {
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(activity, Uri.parse(filePath));
            player.setOnPreparedListener(this);
            player.setOnCompletionListener(this);
            thumb.setVisibility(View.VISIBLE);
            loading.setVisibility(View.VISIBLE);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        rl_video.setVisibility(View.VISIBLE);
        postImage.setVisibility(View.GONE);
    } else {
        thumb.setVisibility(View.GONE);
        postImage.setVisibility(View.VISIBLE);
        rl_video.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
        Glide.with(activity)
                .load(filePath).centerCrop().listener(new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                postImage.setScaleType(ImageView.ScaleType.CENTER);
                postImage.setImageResource(R.drawable.ic_avatar);
                loading.setVisibility(View.GONE);
                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                loading.setVisibility(View.GONE);
                return false;
            }
        }).into(postImage);
    }
}

@Override
public void onPrepared(MediaPlayer mp) {
    player.start();
    loading.setVisibility(View.GONE);
    thumb.setVisibility(View.GONE);
}
@Override
public void onCompletion(MediaPlayer mp) {
    mp.release();
    try {
        final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
        final int pos;
        position = viewPager.getCurrentItem();
        if (position == depate.getPost().size() - 1) {
            try {
                getActivity().finish();
            } catch (Exception e) {
            }
        } else {
            pos = position;
             viewPager.setCurrentItem(pos + 1);

        }
    } catch (Exception e) {
    }
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (this.isVisible()) {
        if (!isVisibleToUser) {
            if (player != null) {
                player.release();
            }
        }else player.start();
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    try {
        player.setDisplay(holder);
        player.prepareAsync();
    } catch (Exception e) {
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}

}

activity_posts_views.xml

       <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#000000" />

fragment_demo_object.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_view_post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff000000"
android:fitsSystemWindows="true"
android:orientation="vertical">


        <RelativeLayout
            android:id="@+id/rl_media"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#000">

            <RelativeLayout
                android:id="@+id/rl_video"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="visible">

                <FrameLayout
                    android:id="@+id/videoSurfaceContainer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <SurfaceView
                        android:id="@+id/videoSurface"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </FrameLayout>

                <ImageView
                    android:id="@+id/thumb"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:background="@drawable/white_circle_opacity"
                    android:padding="5dp"
                    android:src="@drawable/evp_action_play" />
            </RelativeLayout>

            <ImageView
                android:id="@+id/postImage"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerInParent="true"
                android:background="#000"
                android:visibility="visible" />

            <ProgressBar
                android:id="@+id/loading"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:visibility="gone" />
        </RelativeLayout>
   </RelativeLayout>

Debate.class

      public class Debate implements Serializable {

String CreatedAt;
String key;
ArrayList<Post> Post;
public Debate(String key, ArrayList<Post> posts, String createdAt) {
    this.key = key;
    this.Post = posts;
    this.CreatedAt = createdAt;
}
public ArrayList<Post> getPost() {
    return Post;
}

public void setPost(ArrayList<Post> Post) {
    this.Post = Post;
}

public String getCreatedAt() {
    return CreatedAt;
}

public void setCreatedAt(String CreatedAt) {
   this. CreatedAt = CreatedAt;
}

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}
}

Post.class

 public class Post implements Serializable {
String DebateId;
String PostId;
int PostType;
String FilePath;

public Post(String debateId, String postId, int postType, String filePath) {
    DebateId = debateId;
    PostId = postId;
    PostType = postType;
    FilePath = filePath;
}

public String getPostId() {
    return PostId;
}

public void setPostId(String postId) {
    PostId = postId;
}

public String getDebateId() {
    return DebateId;
}

public void setDebateId(String DebateId) {
    this.DebateId = DebateId;
}

public int getPostType() {
    return PostType;
}

public void setPostType(int PostType) {
    this.PostType = PostType;
}

public String getFilePath() {
    return FilePath;
}

public void setFilePath(String FilePath) {
    this.FilePath = FilePath;
}

}


回答1:


You can write your custom viewpager by copy the viewpager's source like below sample class:

https://gist.github.com/anonymous/24831ea667540ab6a43cc777b7e38a65

Let me know if it works for you.



来源:https://stackoverflow.com/questions/45052603/video-image-viewpager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!