一、近期有一个需求要实现一款定制化开发的一款广告轮播视频+图片+音频的结合,来吧接下来操作起来.因为发现Viewpager 轮播的监听总会频繁调用导致体验不太好 这边是使用RecyclerView+Handler的结合实现.
1.先看一下实现效果吧 这边是有音频的情况下先播放音频,音频播放结束以后会播放视频声音,并实现了轮播的效果.
2.直接上代码吧 ,MainActivity页面
package com.example.lunbo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.VideoView;
import com.example.lunbo.utils.PlayerUtils;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private static final int FLAG_NEXT = 10000;
private MyHandler myHandler = new MainActivity.MyHandler(this);
public RotationAdapter adapter;
private int tempPosition = 0;
private List<MediaDetailBean> mList = new ArrayList<MediaDetailBean>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
String muPath = "android.resource://" + this.getPackageName() + "/" + R.raw.auy;
adapter = new RotationAdapter(mList);
ViewPagerLayoutManager layoutManager = new ViewPagerLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
layoutManager.setOnViewPagerListener(new OnViewPagerListener() {
@Override
public void onInitComplete() {
MediaDetailBean mediaDetailBean = adapter.getData().get(0);
myHandler.removeCallbacksAndMessages(null);
if (mediaDetailBean.getItemType() == 1) {
Message message = myHandler.obtainMessage();
message.what = FLAG_NEXT;
message.obj = 1;
long start = PlayerUtils.getInstance().start(MainActivity.this, muPath, new OnCompletionListener() {
@Override
public void onCompletion() {
}
});
myHandler.sendMessageDelayed(message, start);
} else {
View viewByPosition = layoutManager.findViewByPosition(0);
if (viewByPosition != null) {
VideoView videoView = viewByPosition.findViewById(R.id.video_view);
videoView.setVideoPath(mediaDetailBean.getUri());
videoView.start();
PlayerUtils.getInstance().start(MainActivity.this, muPath, () -> videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(1, 1)));
videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(0f, 0f));
Message message = myHandler.obtainMessage();
message.what = FLAG_NEXT;
message.obj = 1;
myHandler.sendMessageDelayed(message, mediaDetailBean.getDuration());
}
}
}
@Override
public void onPageRelease(boolean isNext, int position) {
}
@Override
public void onPageSelected(int position, boolean isBottom) {
PlayerUtils.getInstance().stop();
MediaDetailBean mediaDetailBean = adapter.getData().get(position);
myHandler.removeCallbacksAndMessages(null);
tempPosition = position;
if (mediaDetailBean.getItemType() == 2) {
View viewByPosition = layoutManager.findViewByPosition(position);
if (viewByPosition != null) {
VideoView videoView = viewByPosition.findViewById(R.id.video_view);
videoView.setVideoPath(mediaDetailBean.getUri());
videoView.start();
PlayerUtils.getInstance().start(MainActivity.this, muPath, new OnCompletionListener() {
@Override
public void onCompletion() {
String name = videoView.getClass().getName();
try {
Field age = videoView.getClass().getDeclaredField("mMediaPlayer");
age.setAccessible(true);
MediaPlayer o = (MediaPlayer) age.get(videoView);
o.setVolume(1, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
videoView.setOnPreparedListener(mediaPlayer -> mediaPlayer.setVolume(0f, 0f));
Message message = myHandler.obtainMessage();
message.what = FLAG_NEXT;
tempPosition += 1;
message.obj = tempPosition;
myHandler.sendMessageDelayed(message, mediaDetailBean.getDuration());
}
} else if (mediaDetailBean.getItemType() == 1) {
Message message = myHandler.obtainMessage();
message.what = FLAG_NEXT;
tempPosition += 1;
message.obj = tempPosition;
long start = PlayerUtils.getInstance().start(MainActivity.this, muPath, null);
myHandler.sendMessageDelayed(message, start);
}
}
});
recyclerView.setAdapter(adapter);
initData();
}
private void initData() {
for (int i = 0; i < 4; i++) {
if (i % 2 == 1) {
String path2 = "android.resource://" + this.getPackageName() + "/" + R.raw.video1;
MediaDetailBean detailBean = new MediaDetailBean();
detailBean.setType(2);
detailBean.setUri(path2);
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, Uri.parse(path2));
String s = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
detailBean.setDuration(Long.parseLong(s));
mList.add(detailBean);
} else {
String path1 = "android.resource://" + this.getPackageName() + "/" + R.raw.img;
MediaDetailBean detailBean2 = new MediaDetailBean();
detailBean2.setType(1);
detailBean2.setUri(path1);
detailBean2.setDuration(5000);
mList.add(detailBean2);
}
}
adapter.notifyDataSetChanged();
}
private static class MyHandler extends Handler {
private WeakReference<MainActivity> weakReference;
public MyHandler(MainActivity activity) {
this.weakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == FLAG_NEXT) {
int obj = (int) msg.obj;
if (weakReference.get() != null) {
if (weakReference.get().adapter.getData().size() == obj) {
obj = 0;
}
if (obj == 0) {
weakReference.get().recyclerView.scrollToPosition(obj);
} else {
weakReference.get().recyclerView.smoothScrollToPosition(obj);
}
}
}
}
}
}
3.接下来main_activity.xml配置文件
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"
/>
</RelativeLayout>
4.适配器来了
package com.example.lunbo;
import android.media.MediaPlayer;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.VideoView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import java.util.List;
public class RotationAdapter extends BaseMultiItemQuickAdapter<MediaDetailBean, BaseViewHolder> {
public RotationAdapter(List<MediaDetailBean> data) {
super(data);
addItemType(1, R.layout.layout_image);
addItemType(2, R.layout.layout_video);
}
@Override
protected void convert(BaseViewHolder helper, MediaDetailBean item) {
switch (helper.getItemViewType()) {
case 1:
ImageView imageView = helper.getView(R.id.img_view);
Glide.with(MyApp.context).load(item.getUri()).into(imageView);
break;
case 2:
break;
}
}
}
5.这边自定义适配器管理器
package com.example.lunbo;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
public class ViewPagerLayoutManager extends LinearLayoutManager {
private PagerSnapHelper mPagerSnapHelper;
private OnViewPagerListener mOnViewPagerListener;
private RecyclerView mRecyclerView;
private int mDrift = 0;
public ViewPagerLayoutManager(Context context) {
super(context);
init();
}
public ViewPagerLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
init();
}
public ViewPagerLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
mPagerSnapHelper = new PagerSnapHelper();
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
mPagerSnapHelper.attachToRecyclerView(view);
this.mRecyclerView = view;
mRecyclerView.addOnChildAttachStateChangeListener(mChildAttachStateChangeListener);
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
switch (state) {
case RecyclerView.SCROLL_STATE_IDLE:
View snapView = mPagerSnapHelper.findSnapView(this);
if (snapView == null) return;
int positionIdle = getPosition(snapView);
if (mOnViewPagerListener != null) {
mOnViewPagerListener.onPageSelected(positionIdle, positionIdle == getChildCount() - 1);
}
break;
case RecyclerView.SCROLL_STATE_DRAGGING:
View viewDrag = mPagerSnapHelper.findSnapView(this);
if (viewDrag != null) {
int positionDrag = getPosition(viewDrag);
}
break;
case RecyclerView.SCROLL_STATE_SETTLING:
View viewSettling = mPagerSnapHelper.findSnapView(this);
if (viewSettling != null) {
int positionSettling = getPosition(viewSettling);
}
break;
}
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
mDrift = dy;
return super.scrollVerticallyBy(dy, recycler, state);
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
mDrift = dx;
return super.scrollHorizontallyBy(dx, recycler, state);
}
public void setOnViewPagerListener(OnViewPagerListener listener) {
mOnViewPagerListener = listener;
}
private RecyclerView.OnChildAttachStateChangeListener mChildAttachStateChangeListener = new RecyclerView.OnChildAttachStateChangeListener() {
@Override
public void onChildViewAttachedToWindow(@NonNull View view) {
if (mOnViewPagerListener != null && getChildCount() == 1) {
mOnViewPagerListener.onInitComplete();
}
}
@Override
public void onChildViewDetachedFromWindow(@NonNull View view) {
if (mDrift >= 0) {
if (mOnViewPagerListener != null)
mOnViewPagerListener.onPageRelease(true, getPosition(view));
} else {
if (mOnViewPagerListener != null)
mOnViewPagerListener.onPageRelease(false, getPosition(view));
}
if (mOnViewPagerListener != null) {
mOnViewPagerListener.onPageRelease(true, getPosition(view));
}
}
};
}
6.定义了一个实体类
package com.example.lunbo;
import android.net.Uri;
import com.chad.library.adapter.base.entity.MultiItemEntity;
public class MediaDetailBean implements MultiItemEntity {
private int type;
private String uri;
private long duration;
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Override
public int getItemType() {
return type;
}
}
7.定义接口用于回调
package com.example.lunbo;
public interface OnViewPagerListener {
void onInitComplete();
void onPageRelease(boolean isNext, int position);
void onPageSelected(int position, boolean isBottom);
}
8.定义接口
package com.example.lunbo;
public interface OnCompletionListener {
void onCompletion();
}
9.接下来是视频适配器的配置文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<VideoView
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
10.这里是图片适配器的配置文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/img_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
</RelativeLayout>
然后就结束了下面附源码地址:网盘链接:链接:https://pan.baidu.com/s/1LLpPcoA_SVCwCQr1aZ1AJA 提取码:adga
码云地址:https://gitee.com/nuanmou/guanggao
|