IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> android 广告轮播图片+视频+音频 -> 正文阅读

[移动开发]android 广告轮播图片+视频+音频

一、近期有一个需求要实现一款定制化开发的一款广告轮播视频+图片+音频的结合,来吧接下来操作起来.因为发现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;

/**
 * @author Lenovo
 */
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) {
                    //判断第一条数据设置0
                    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));
                        //判断第一条数据设置0
                        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));
                        //判断第一条数据设置0
                        Message message = myHandler.obtainMessage();
                        message.what = FLAG_NEXT;
                        tempPosition += 1;
                        message.obj = tempPosition;
                        myHandler.sendMessageDelayed(message, mediaDetailBean.getDuration());
                    }

                } else if (mediaDetailBean.getItemType() == 1) {
                    //判断第一条数据设置0
                    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;
                //判断Activity是否存在
                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;

/**
 * @ProjectName : Lunbo
 * @Author : 白月初
 * @Time : 2022/3/1 15:54
 * @Description : 描述
 */
public class RotationAdapter extends BaseMultiItemQuickAdapter<MediaDetailBean, BaseViewHolder> {
    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    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;
        }
    }

//    @Override
//    public int getItemCount() {
//        return Integer.MAX_VALUE;
//    }
}

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;

/**
 * @author Lenovo
 */
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 && getChildCount() == 1) {
                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);
    }


    /**
     * 设置监听
     *
     * @param listener
     */
    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;

/**
 * Copyright (C), 2020-2021
 * Description:
 *
 * @author xj.luo
 * Email: xj_luo@foxmail.com
 */
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;

/**
 * @author Lenovo
 */
public interface OnViewPagerListener {

    /**
     * 初始化完成
     */
    void onInitComplete();

    /**
     * 释放的监听
     */
    void onPageRelease(boolean isNext, int position);

    /**
     * 选中的监听以及判断是否滑动到底部
     */
    void onPageSelected(int position, boolean isBottom);
}

8.定义接口

package com.example.lunbo;

/**
 * @author Lenovo
 */
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

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-03-17 22:19:09  更:2022-03-17 22:19:42 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 19:01:11-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码