用到的第三方框架:
GSYVideoPlayer
XPopup
AndPermission
1.布局
AntVideoNoBlackPlayer
来之GSYVideoPlayer
自己对此进行了一些自定义
<LinearLayout
android:id="@+id/layout_imgs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView51">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/shape_solid_white_stroke_ccc_5" />
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="8dp"
android:src="@drawable/shape_solid_white_stroke_ccc_5" />
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="8dp"
android:src="@drawable/shape_solid_white_stroke_ccc_5" />
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="8dp"
android:src="@drawable/shape_solid_white_stroke_ccc_5" />
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="8dp"
android:src="@drawable/shape_solid_white_stroke_ccc_5" />
<com.xqd.video.custom.AntVideoNoBlackPlayer
android:id="@+id/video_player"
android:layout_width="match_parent"
android:layout_height="60dp"
/>
</LinearLayout>
2.动态的设置布局,图片的宽高,视频的宽高
BlogInfo
为我自己的数据对象,
public class LayoutVideoImgUtils {
private static int realWidth;
private static LinearLayout.LayoutParams layoutImgParams;
private static LinearLayout.LayoutParams layoutImgEndParams;
private static LinearLayout.LayoutParams layoutVideoParams;
static {
realWidth = ScreenUtils.getRealWidth()- DpPxUtils.dp2px(32);
int videoWidth = realWidth/3*2;
int imgWidth = (realWidth-DpPxUtils.dp2px(32))/5;
layoutImgParams = new LinearLayout.LayoutParams(imgWidth, imgWidth);
layoutImgEndParams = new LinearLayout.LayoutParams(imgWidth, imgWidth);
layoutImgParams.setMargins(0,0,DpPxUtils.dp2px(8),0);
layoutVideoParams = new LinearLayout.LayoutParams(videoWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
}
public static void setImgVideo(LinearLayout layoutImgs, BlogInfo item){
String videoCover = item.getVideo_cover();
if (TextUtils.isEmpty(videoCover)){//图片类型
LayoutVideoImgUtils.setImgView(layoutImgs,item.getImages_thumb(),item.getImages());
}else {//视频类型
LayoutVideoImgUtils.setVideoView(layoutImgs,item);
}
}
/**
* 设置视频文件
*/
private static void setVideoView(LinearLayout layoutImgs, BlogInfo item) {
//控件显示隐藏
layoutImgs.setVisibility(View.VISIBLE);
String videoUrl = item.getVideo();
String videoCover = item.getVideo_cover();
int width = item.getWidth();
int height = item.getHeight();
for (int i = 0; i < 5; i++) {
ImageView iv = (ImageView) layoutImgs.getChildAt(i);
iv.setVisibility(View.GONE);
}
AntVideoNoBlackPlayer videoPlayer = (AntVideoNoBlackPlayer) layoutImgs.getChildAt(5);
videoPlayer.setVisibility(View.VISIBLE);
//横向视频:宽度铺满,高度自适应
float scale = (float) height/(float)width;
int videoHeight = (int) (scale * realWidth);
if (width>height){
layoutVideoParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, videoHeight);
}else {//竖向视频:宽度为屏幕的2/3,高度等比例缩放
layoutVideoParams = new LinearLayout.LayoutParams(realWidth/3*2, videoHeight/3*2);
}
videoPlayer.setLayoutParams(layoutVideoParams);
setVideoConfig(layoutImgs.getContext(),videoPlayer,videoCover,videoUrl,width>height);
}
private static void setVideoConfig(Context mContext, AntVideoNoBlackPlayer videoPlayer, String videoCover, String videoUrl, boolean isHorizontical){
videoPlayer.setLayoutParams(layoutVideoParams);
//视频基本配置
videoPlayer.getBackButton().setVisibility(View.GONE);//隐藏返回按钮
videoPlayer.setVisibility(View.VISIBLE); //显示隐藏控件
videoPlayer.setLooping(true);//循环播放
videoPlayer.setThumbPlay(true);
videoPlayer.setIsTouchWiget(false);//关闭触摸小控件
//视频背景,防止暂停后黑屏
ImageView layoutRoot = videoPlayer.getLayoutRoot();
layoutRoot.setScaleType(isHorizontical?ImageView.ScaleType.FIT_XY:ImageView.ScaleType.CENTER_CROP);
Glide.with(mContext).load(videoCover).into(layoutRoot);
//设置视频封面,防止未播放时黑屏
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(isHorizontical?ImageView.ScaleType.FIT_CENTER:ImageView.ScaleType.CENTER_CROP);
Glide.with(imageView).load(videoCover).into(imageView);
videoPlayer.setThumbImageView(imageView);
//设置视频地址
videoPlayer.setUp(videoUrl, true, "");
}
/**
* 设置图片集合
* @param images
*/
private static void setImgView(LinearLayout layoutImgs, List<String> thumbImages, List<String> images) {
if (images.size()==0){
layoutImgs.setVisibility(View.GONE);
return;
}else{
layoutImgs.setVisibility(View.VISIBLE);
layoutImgs.getChildAt(5).setVisibility(View.GONE);
}
for (int i = 0; i < 5; i++) {
ImageView iv = (ImageView) layoutImgs.getChildAt(i);
iv.setLayoutParams((i==4)?layoutImgEndParams:layoutImgParams);
}
//图片控件显示,并加载图片
int size = thumbImages.size();
//需要大图浏览的图片集合
List<Object> imgs = new ArrayList<>();
for (String image : images) imgs.add(image);
for (int i = 0; i < size; i++) {
String imgUrl = thumbImages.get(i);
ImageView iv = (ImageView) layoutImgs.getChildAt(i);
iv.setVisibility(View.VISIBLE);
DataBindAdapter.roundUrl(iv,imgUrl,6);
int finalI = i;
iv.setOnClickListener(v -> PopShowUtils.showPics(layoutImgs,imgs, finalI));
}
//多余图片控件隐藏
if (size<5)for (int i = size; i <5 ; i++) {
ImageView iv = (ImageView)layoutImgs.getChildAt(i);
iv.setVisibility(View.GONE);
}
}
}
3.展示图片或播放视频
目前采用的本页列表来播放,也可以通过弹框来播放,使用了XPopup,AndPermission
public class PopShowUtils {
/**
* 弹窗多图浏览
* @param layoutImgs 装载图片的控制器:5张固定图片ImageView
* @param images 图片集合
* @param position 点击图片的位置
*/
public static void showPics(LinearLayout layoutImgs, List<Object> images, int position) {
ImageView iv = (ImageView) layoutImgs.getChildAt(position);
Context context = layoutImgs.getContext();
ImageViewerPopupView popView = new BigPicsPopupView(context);
popView.setSrcView(iv, position).setImageUrls(images)
.isInfinite(false)//必须false,否则第5个位置,不是ImageView,报错
.isShowSaveButton(false)
.setXPopupImageLoader(new BigPicPopImageLoader());
popView.setSrcViewUpdateListener((popupView, index) -> popView.updateSrcView((ImageView) layoutImgs.getChildAt(index)));
new XPopup.Builder(context)
.asCustom(popView).show();
}
//弹出一个全窗口来播放
public static void showVideo(Context context, String videoCover, String videoUrl) {
new XPopup.Builder(context)
.asCustom(new FullScreenVideoPop(context, videoCover, videoUrl))
.show();
}
}
其中BigPicsPopupView
主要解决权限,和Android10图片的保存,不保存的就可以直接使用ImageViewerPopupView
public class BigPicsPopupView<T> extends ImageViewerPopupView implements OnDragChangeListener, View.OnClickListener{
public BigPicsPopupView(@NonNull Context context) {
super(context);
}
@Override
protected void save() {
AndPermission.with(getContext())
.runtime()
.permission(Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
.onGranted(permissions -> {
Object uri = urls.get(isInfinite ? position % urls.size() : position);
saveNetPic(getContext(),uri);
// XPopupUtils.saveBmpToAlbum(getContext(), imageLoader, urls.get(isInfinite ? position % urls.size() : position));
})
.onDenied(permissions -> {
ToastUtil.showLong("权限被拒绝!");
})
.start();
}
private void saveNetPic(final Context mContext, Object uri){
final Handler mainHandler = new Handler(Looper.getMainLooper());
final ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
File source = imageLoader.getImageFile(mContext, uri);
try {
//1. create path
String dirPath = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
File dirFile = new File(dirPath);
if (!dirFile.exists()) dirFile.mkdirs();
ImageType type = ImageHeaderParser.getImageType(new FileInputStream(source));
String ext = getFileExt(type);
final File target = new File(dirPath, System.currentTimeMillis() + "." + ext);
if (target.exists()) target.delete();
target.createNewFile();
//2. save,保存到本应用目录
writeFileFromIS(target, new FileInputStream(source));
//3. notify
MediaScannerConnection.scanFile(mContext, new String[]{target.getAbsolutePath()},
new String[]{"image/" + ext}, (path, uri1) -> mainHandler.post(() -> {
Toast.makeText(mContext, "已保存到相册!", Toast.LENGTH_SHORT).show();
//4.保存到相册
try {
Bitmap bitmap = BitmapFactory.decodeFile(target.getAbsolutePath());
saveBitmap(getContext(),bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}));
} catch (IOException e) {
e.printStackTrace();
}
});
}
public void saveBitmap(Context context, Bitmap bitmap) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DESCRIPTION, "This is an image");
values.put(MediaStore.Images.Media.DISPLAY_NAME, "Image.png");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis()+".png");
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera");
Uri external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver resolver = context.getContentResolver();
Uri insertUri = resolver.insert(external, values);
OutputStream os = null;
if (insertUri != null) {
try {
os = resolver.openOutputStream(insertUri);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, os);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static boolean writeFileFromIS(final File file, final InputStream is) {
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
byte data[] = new byte[8192];
int len;
while ((len = is.read(data, 0, 8192)) != -1) {
os.write(data, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getFileExt(ImageType type) {
switch (type) {
case GIF:
return "gif";
case PNG:
case PNG_A:
return "png";
case WEBP:
case WEBP_A:
return "webp";
case JPEG:
return "jpeg";
}
return "jpeg";
}
}
全屏播放的FullScreenVideoPop
为:
public class FullScreenVideoPop extends FullScreenPopupView {
String videoCover;
String videoUrl;
public FullScreenVideoPop(@NonNull Context context,String videoCover,String videoUrl) {
super(context);
this.videoCover = videoCover;
this.videoUrl = videoUrl;
}
@Override
protected int getImplLayoutId() {
return R.layout.pop_full_screen_video;
}
@Override
protected void onCreate() {
super.onCreate();
AntVideoPlayer videoPlayer = findViewById(R.id.video_player);
videoPlayer.setUp(videoUrl,true, "");
videoPlayer.setLooping(true);
videoPlayer.setThumbPlay(true);
videoPlayer.setStartAfterPrepared(true);
videoPlayer.setReleaseWhenLossAudio(false);
videoPlayer.setIsTouchWiget(false);
videoPlayer.getBackButton().setVisibility(GONE);
//视频背景
ImageView layoutRoot = videoPlayer.getLayoutRoot();
Glide.with(getContext())
.load(videoCover)
.into(layoutRoot);
//封面
ImageView ivCover = new ImageView(this.getContext());
ivCover.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(ivCover).load(videoCover).into(ivCover);
videoPlayer.setThumbImageView(ivCover);
//视频的裁剪方式
videoPlayer.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT);
ImageView backButton = videoPlayer.getBackButton();
backButton.setImageResource(R.mipmap.ic_back_white);
backButton.setOnClickListener(v -> dismiss());
videoPlayer.startPlayLogic();
findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
@Override
protected void onDismiss() {
super.onDismiss();
GSYVideoManager.onPause();
}
}
布局文件pop_full_screen_video
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.xqd.video.custom.AntVideoPlayer
android:id="@+id/video_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"/>
<ImageView
android:id="@+id/iv_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:padding="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@mipmap/ic_back_white" />
</androidx.constraintlayout.widget.ConstraintLayout>
最后的效果:

网友评论