王鹏鹏 преди 2 години
родител
ревизия
1dead4fa26

+ 3 - 0
baselib/build.gradle

@@ -128,4 +128,7 @@ dependencies {
     api ("com.google.android:flexbox:2.0.1")
     //api 'lib.gorden.rxbus2:rxbus:2.0.1'
     api 'io.github.jeremyliao:live-event-bus-x:1.8.0'
+
+    api 'com.github.bumptech.glide:glide:4.9.0'
+    kapt 'com.github.bumptech.glide:compiler:4.9.0'
 }

+ 100 - 0
baselib/src/main/java/com/yingyangfly/baselib/img/GlideRoundTransform.java

@@ -0,0 +1,100 @@
+package com.yingyangfly.baselib.img;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapShader;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.RectF;
+
+import androidx.annotation.NonNull;
+
+import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
+import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
+import com.bumptech.glide.util.Util;
+
+import java.nio.ByteBuffer;
+import java.security.MessageDigest;
+
+public class GlideRoundTransform extends BitmapTransformation {
+
+    private static final String ID = "com.xiaohe.www.lib.tools.glide.GlideRoundTransform";
+
+    private static final byte[] ID_BYTES = ID.getBytes(CHARSET);
+
+    private int radius;
+
+    public GlideRoundTransform(Context context, int radius) {
+
+        this.radius = dip2px(context,radius);
+
+    }
+
+    @Override
+
+    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
+
+        int width = toTransform.getWidth();
+
+        int height = toTransform.getHeight();
+
+        Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
+
+        bitmap.setHasAlpha(true);
+
+        Canvas canvas = new Canvas(bitmap);
+
+        Paint paint = new Paint();
+
+        paint.setAntiAlias(true);
+
+        paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
+
+        canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
+
+        return bitmap;
+
+    }
+
+    @Override
+
+    public boolean equals(Object obj) {
+
+        if (obj instanceof GlideRoundTransform) {
+
+            GlideRoundTransform other = (GlideRoundTransform) obj;
+
+            return radius == other.radius;
+
+        }
+
+        return false;
+
+    }
+
+    @Override
+
+    public int hashCode() {
+
+        return Util.hashCode(ID.hashCode(), Util.hashCode(radius));
+
+    }
+
+    @Override
+
+    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
+
+        messageDigest.update(ID_BYTES);
+
+        byte[] radiusData = ByteBuffer.allocate(4).putInt(radius).array();
+
+        messageDigest.update(radiusData);
+
+    }
+
+    //dp转px
+    public int dip2px(Context context, float dpValue) {
+        final float scale = context.getResources().getDisplayMetrics().density;
+        return (int) (dpValue * scale + 0.5f);
+    }
+}

+ 251 - 0
baselib/src/main/java/com/yingyangfly/baselib/img/ImgUtil.java

@@ -0,0 +1,251 @@
+package com.yingyangfly.baselib.img;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Matrix;
+import android.graphics.drawable.Drawable;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+
+import androidx.annotation.NonNull;
+
+import com.bumptech.glide.Glide;
+import com.bumptech.glide.load.engine.DiskCacheStrategy;
+import com.bumptech.glide.load.resource.bitmap.CenterCrop;
+import com.bumptech.glide.load.resource.bitmap.CircleCrop;
+import com.bumptech.glide.request.RequestOptions;
+import com.bumptech.glide.request.target.SimpleTarget;
+import com.bumptech.glide.request.transition.Transition;
+import com.yingyangfly.baselib.R;
+
+import java.io.ByteArrayOutputStream;
+
+import io.reactivex.annotations.Nullable;
+
+/**
+ * Author: YongChao
+ * Date: 19-8-21 下午5:49
+ * Description:
+ */
+public class ImgUtil {
+
+    public static void loadImgFace(Context context, String face_url, final ImageView img) {
+        RequestOptions options = new RequestOptions()
+                .fitCenter()
+                .diskCacheStrategy(DiskCacheStrategy.NONE);
+        Glide.with(context)
+                .load(face_url)
+                .into(new SimpleTarget<Drawable>() {
+                    @Override
+                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
+                        img.setImageDrawable(resource);
+                    }
+                });
+    }
+
+    public static void loadImgCircle(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+        Glide.with(context).load(imgUrl).apply(options).into(img);
+    }
+
+    public static void loadImgHeadCircle(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
+                .diskCacheStrategy(DiskCacheStrategy.NONE);
+
+        Glide.with(context).load(imgUrl).apply(options).into(img);
+    }
+
+    public static void loadAvatarRound(Context context, String imgUrl, ImageView img) {
+//        RequestOptions options = new RequestOptions()
+//                .placeholder( R.drawable.ic_avatar)
+//                .error( R.drawable.ic_avatar)
+//                .transform(new CenterCrop(),new GlideRoundTransform(context, 5))
+//                .diskCacheStrategy(DiskCacheStrategy.ALL);
+//
+//        Glide.with(context).load(imgUrl).apply(options).into(img);
+    }
+
+    public static void loadImgCircle(Context context, String imgUrl, ImageView img) {
+//        loadImgCircle(context, imgUrl, img, R.drawable.icon_assistant_head, R.drawable.icon_assistant_head);
+    }
+
+    /**
+     * @param: [context, imgUrl, img]
+     * @return: void
+     * @description: 设置加载占位符及加载失败
+     */
+    public static void loadImgPlaceHolderError(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+
+        Glide.with(context).load(imgUrl).apply(options).into(img);
+    }
+
+    public static void loadImg(Context context, String imgUrl, ImageView img) {
+//        loadImgPlaceHolderError(context, imgUrl, img, R.drawable.ic_avatar, R.drawable.ic_avatar);
+    }
+
+    public static void loadImgNoPlaceHolder(Context context, String imgUrl, ImageView img) {
+        RequestOptions options = new RequestOptions()
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+        Glide.with(context).load(imgUrl).apply(options).into(img);
+    }
+
+    public static void loadGifImg(Context context, int imgUrl, ImageView img) {
+        Glide.with(context).asGif().load(imgUrl).into(img);
+    }
+
+    public static void zoomImg(Context context, String imgUrl, ImageView img) {
+        Glide.with(context)
+                .asBitmap()
+                .load(imgUrl)
+                .into(new TransformationUtils(img));
+    }
+
+    /**
+     * 圆角图片
+     *
+     * @param context
+     * @param imgUrl
+     * @param img
+     * @param dPlaceHolder
+     * @param dError
+     */
+    public static void loadRoundImg(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError) {
+        loadRoundImg(context,imgUrl,img,dPlaceHolder,dError,5);
+    }
+
+    public static void loadRoundImg(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError,int radius) {
+
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+
+        Glide.with(context).load(imgUrl).transform(new GlideRoundTransform(context, radius)).apply(options).into(img);
+    }
+
+    public static void loadRoundImg(Context context, int imgLocoalSrc, ImageView img,int radius) {
+        Glide.with(context).load(imgLocoalSrc).transform(new GlideRoundTransform(context, radius)).into(img);
+    }
+
+    public static void loadRoundImg(Context context, String imgUrl, ImageView img) {
+//        loadRoundImg(context, imgUrl, img, R.drawable.ic_qr_place_holder, R.drawable.ic_qr_place_holder);
+    }
+
+    public static void loadBitmap(Context context, Bitmap bitmap, ImageView imageView) {
+        Glide.with(context).load(bitmap).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
+    }
+
+    public static void loadImage(Context context, int id, ImageView imageView) {
+        Glide.with(context).load(id).into(imageView);
+    }
+
+    /**
+     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
+     *
+     * @param bitmap
+     * @param maxKb
+     * @return
+     */
+    public static byte[] bmpToByteArray(Bitmap bitmap, long maxKb, boolean needRecycle) {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
+//        LogUtil.Companion.i("output " + output.toByteArray().length);
+//        LogUtil.Companion.i("output maxKb " + maxKb);
+        int options = 100;
+//        int fileSize = output.toByteArray().length;
+//        options = (int) Math.max(1, maxKb * 100 / fileSize);
+//        LogUtil.Companion.i("output option " + options);
+        while (output.toByteArray().length > maxKb && options > 0) {
+            output.reset(); //清空output
+            bitmap.compress(
+                    Bitmap.CompressFormat.JPEG,
+                    options,
+                    output
+            ); //这里压缩options%,把压缩后的数据存放到output中
+//            LogUtil.Companion.i("output " + output.toByteArray().length);
+            options -= 10;
+        }
+        if (needRecycle) {
+            bitmap.recycle();
+        }
+        return output.toByteArray();
+    }
+
+
+
+    /**
+     * 加载自定义宽高圆角图片
+     */
+    public static void loadRoundImgWidth(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError,int radius,int width) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+
+        ViewGroup.LayoutParams params = img.getLayoutParams();
+        params.height = width;
+        params.width = width;
+        img.setLayoutParams(params);
+
+        Glide.with(context).load(imgUrl).transform(new GlideRoundTransform(context, radius)).apply(options).into(img);
+    }
+
+    /**
+     * 加载自定义宽高圆角图片
+     */
+    public static void loadRoundImgWidthThumbnail(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError,int radius,int width) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+
+        ViewGroup.LayoutParams params = img.getLayoutParams();
+        params.height = width;
+        params.width = width;
+        img.setLayoutParams(params);
+
+        Glide.with(context).load(imgUrl).thumbnail(0.1f).transform(new GlideRoundTransform(context, radius)).apply(options).into(img);
+    }
+
+    /**
+     * 加载自定义宽高圆角图片
+     */
+    public static void loadRoundImgWidthThumbnail(Context context, String imgUrl, ImageView img, int dPlaceHolder, int dError,int radius,int width,float sizeMultiplier) {
+        RequestOptions options = new RequestOptions()
+                .placeholder(dPlaceHolder)
+                .error(dError)
+                .diskCacheStrategy(DiskCacheStrategy.ALL);
+
+        ViewGroup.LayoutParams params = img.getLayoutParams();
+        params.height = width;
+        params.width = width;
+        img.setLayoutParams(params);
+
+        Glide.with(context).load(imgUrl).thumbnail(sizeMultiplier).transform(new GlideRoundTransform(context, radius)).apply(options).into(img);
+    }
+
+    public static Bitmap convertBitmapSize( Bitmap bm, int newWidth, int newHeight) { // 获得图片的宽高
+        int width = bm.getWidth();
+        int height = bm.getHeight();
+        // 计算缩放比例
+        float scaleWidth = Float.parseFloat(newWidth+"") / width;
+        float scaleHeight = Float.parseFloat(newHeight+"")/ height;
+        // 取得想要缩放的matrix参数
+        Matrix matrix = new Matrix();
+        matrix.postScale(scaleWidth, scaleHeight);
+        // 得到新的图片
+        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
+    }
+
+}

+ 50 - 0
baselib/src/main/java/com/yingyangfly/baselib/img/SaveBitmapToPhoto.java

@@ -0,0 +1,50 @@
+package com.yingyangfly.baselib.img;
+
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.os.Environment;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class SaveBitmapToPhoto {
+    /**
+     * 保存图片到指定路径
+     *
+     * @param context
+     * @param bitmap   要保存的图片
+     * @param fileName 自定义图片名称  getString(R.string.app_name) + "" + System.currentTimeMillis()+".png"
+     * @return true 成功 false失败
+     */
+    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
+        // 保存图片至指定路径
+//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dayixl";
+        //系统相册目录
+        String storePath = Environment.getExternalStorageDirectory()
+                + File.separator + Environment.DIRECTORY_DCIM
+                + File.separator + "Camera" + File.separator;
+        File appDir = new File(storePath);
+        if (!appDir.exists()) {
+            appDir.mkdir();
+        }
+        File file = new File(appDir, fileName);
+        try {
+            FileOutputStream fos = new FileOutputStream(file);
+            //通过io流的方式来压缩保存图片(80代表压缩20%)
+            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
+            fos.flush();
+            fos.close();
+
+            //发送广播通知系统图库刷新数据
+            Uri uri = Uri.fromFile(file);
+            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
+            return isSuccess;
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+}

+ 45 - 0
baselib/src/main/java/com/yingyangfly/baselib/img/TransformationUtils.java

@@ -0,0 +1,45 @@
+package com.yingyangfly.baselib.img;
+
+import android.graphics.Bitmap;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+
+import com.bumptech.glide.request.target.ImageViewTarget;
+
+/**
+ * ===========================================
+ * 版    本:1.0
+ * 描    述:设置图片等比缩放
+ * <p>glide处理图片.</p>
+ * ===========================================
+ */
+public class TransformationUtils extends ImageViewTarget<Bitmap> {
+
+    private ImageView target;
+
+    public TransformationUtils(ImageView target) {
+        super(target);
+        this.target = target;
+    }
+
+    @Override
+    protected void setResource(Bitmap resource) {
+        view.setImageBitmap(resource);
+
+        //获取原图的宽高
+        int width = resource.getWidth();
+        int height = resource.getHeight();
+
+        //获取imageView的宽
+        int imageViewWidth = target.getWidth();
+
+        //计算缩放比例
+        float sy = (float) (imageViewWidth * 0.1) / (float) (width * 0.1);
+
+        //计算图片等比例放大后的高
+        int imageViewHeight = (int) (height * sy);
+        ViewGroup.LayoutParams params = target.getLayoutParams();
+        params.height = imageViewHeight;
+        target.setLayoutParams(params);
+    }
+}

+ 0 - 4
baselib/src/main/java/com/yingyangfly/baselib/net/BaseNetWork.kt

@@ -44,10 +44,6 @@ object BaseNetWork {
                 val original = chain.request()
                 val newOriginal = addParam(original)
                 val request = newOriginal.newBuilder()
-                    .apply {
-//                        if (isLibTypeDoctor()) header("version", "V1") else header("api-version", "v1")
-                    }
-//                    .header("Authorization", "Bearer ${XUser.getLoginToken()}")
                     .header("Content-Type", "application/json")
                     .method(newOriginal.method, newOriginal.body)
                     .build()

+ 233 - 0
baselib/src/main/java/com/yingyangfly/baselib/net/XUtils.java

@@ -0,0 +1,233 @@
+/*
+ * Copyright (C) 2017 zhouyou(478319399@qq.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.yingyangfly.baselib.net;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Looper;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import okhttp3.RequestBody;
+
+/**
+ * <p>描述:工具类</p>
+ * 作者: zhouyou<br>
+ * 日期: 2016/12/20 10:33<br>
+ * 版本: v2.0<br>
+ */
+public class XUtils {
+    public static <T> T checkNotNull(T t, String message) {
+        if (t == null) {
+            throw new NullPointerException(message);
+        }
+        return t;
+    }
+
+    public static boolean checkMain() {
+        return Thread.currentThread() == Looper.getMainLooper().getThread();
+    }
+
+    public static RequestBody createJson(String jsonString) {
+        checkNotNull(jsonString, "json not null!");
+        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonString);
+    }
+
+    /**
+     * @param name
+     * @return
+     */
+    public static RequestBody createFile(String name) {
+        checkNotNull(name, "name not null!");
+        return RequestBody.create(okhttp3.MediaType.parse("multipart/form-data; charset=utf-8"), name);
+    }
+
+    /**
+     * @param file
+     * @return
+     */
+    public static RequestBody createFile(File file) {
+        checkNotNull(file, "file not null!");
+        return RequestBody.create(okhttp3.MediaType.parse("multipart/form-data; charset=utf-8"), file);
+    }
+
+    /**
+     * @param file
+     * @return
+     */
+    public static RequestBody createImage(File file) {
+        checkNotNull(file, "file not null!");
+        return RequestBody.create(okhttp3.MediaType.parse("image/jpg; charset=utf-8"), file);
+    }
+
+    public static void close(Closeable close) {
+        if (close != null) {
+            try {
+                closeThrowException(close);
+            } catch (IOException ignored) {
+            }
+        }
+    }
+
+    public static void closeThrowException(Closeable close) throws IOException {
+        if (close != null) {
+            close.close();
+        }
+    }
+
+    /**
+     * find the type by interfaces
+     *
+     * @param cls
+     * @param <R>
+     * @return
+     */
+    public static <R> Type findNeedType(Class<R> cls) {
+        List<Type> typeList = XUtils.getMethodTypes(cls);
+        if (typeList == null || typeList.isEmpty()) {
+            return RequestBody.class;
+        }
+        return typeList.get(0);
+    }
+
+    /**
+     * MethodHandler
+     */
+    public static <T> List<Type> getMethodTypes(Class<T> cls) {
+        Type typeOri = cls.getGenericSuperclass();
+        List<Type> needtypes = null;
+        // if Type is T
+        if (typeOri instanceof ParameterizedType) {
+            needtypes = new ArrayList<>();
+            Type[] parentypes = ((ParameterizedType) typeOri).getActualTypeArguments();
+            for (Type childtype : parentypes) {
+                needtypes.add(childtype);
+                if (childtype instanceof ParameterizedType) {
+                    Type[] childtypes = ((ParameterizedType) childtype).getActualTypeArguments();
+                    Collections.addAll(needtypes, childtypes);
+                }
+            }
+        }
+        return needtypes;
+    }
+
+    public static Class getClass(Type type, int i) {
+        if (type instanceof ParameterizedType) { // 处理泛型类型     
+            return getGenericClass((ParameterizedType) type, i);
+        } else if (type instanceof TypeVariable) {
+            return getClass(((TypeVariable) type).getBounds()[0], 0); // 处理泛型擦拭对象     
+        } else {// class本身也是type,强制转型     
+            return (Class) type;
+        }
+    }
+
+    public static Type getType(Type type, int i) {
+        if (type instanceof ParameterizedType) { // 处理泛型类型     
+            return getGenericType((ParameterizedType) type, i);
+        } else if (type instanceof TypeVariable) {
+            return getType(((TypeVariable) type).getBounds()[0], 0); // 处理泛型擦拭对象     
+        } else {// class本身也是type,强制转型     
+            return type;
+        }
+    }
+    
+    public static Type getParameterizedType(Type type, int i) {
+        if (type instanceof ParameterizedType) { // 处理泛型类型    
+            return ((ParameterizedType) type).getActualTypeArguments()[i];
+        } else if (type instanceof TypeVariable) {
+            return getType(((TypeVariable) type).getBounds()[0], 0); // 处理泛型擦拭对象     
+        } else {// class本身也是type,强制转型     
+            return type;
+        }
+    }
+
+    public static Class getGenericClass(ParameterizedType parameterizedType, int i) {
+        Type genericClass = parameterizedType.getActualTypeArguments()[i];
+        if (genericClass instanceof ParameterizedType) { // 处理多级泛型     
+            return (Class) ((ParameterizedType) genericClass).getRawType();
+        } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型     
+            return (Class) ((GenericArrayType) genericClass).getGenericComponentType();
+        } else if (genericClass instanceof TypeVariable) { // 处理泛型擦拭对象     
+            return getClass(((TypeVariable) genericClass).getBounds()[0], 0);
+        } else {
+            return (Class) genericClass;
+        }
+    }
+
+    public static Type getGenericType(ParameterizedType parameterizedType, int i) {
+        Type genericType = parameterizedType.getActualTypeArguments()[i];
+        if (genericType instanceof ParameterizedType) { // 处理多级泛型     
+            return ((ParameterizedType) genericType).getRawType();
+        } else if (genericType instanceof GenericArrayType) { // 处理数组泛型     
+            return ((GenericArrayType) genericType).getGenericComponentType();
+        } else if (genericType instanceof TypeVariable) { // 处理泛型擦拭对象     
+            return getClass(((TypeVariable) genericType).getBounds()[0], 0);
+        } else {
+            return genericType;
+        }
+    }
+
+    public static boolean isNetworkAvailable(Context context) {
+        ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(
+                Context.CONNECTIVITY_SERVICE);
+        if (null == manager)
+            return false;
+        NetworkInfo info = manager.getActiveNetworkInfo();
+        return null != info && info.isAvailable();
+    }
+
+
+    /**
+     * 普通类反射获取泛型方式,获取需要实际解析的类型
+     *
+     * @param <T>
+     * @return
+     */
+    public static <T> Type findNeedClass(Class<T> cls) {
+        //以下代码是通过泛型解析实际参数,泛型必须传
+        Type genType = cls.getGenericSuperclass();
+        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
+        Type type = params[0];
+        Type finalNeedType;
+        if (params.length > 1) {//这个类似是:CacheResult<SkinTestResult> 2层
+            if (!(type instanceof ParameterizedType)) throw new IllegalStateException("没有填写泛型参数");
+            finalNeedType = ((ParameterizedType) type).getActualTypeArguments()[0];
+            //Type rawType = ((ParameterizedType) type).getRawType();
+        } else {//这个类似是:SkinTestResult  1层
+            finalNeedType = type;
+        }
+        return finalNeedType;
+    }
+
+    /**
+     * 普通类反射获取泛型方式,获取最顶层的类型
+     */
+    public static <T> Type findRawType(Class<T> cls) {
+        Type genType = cls.getGenericSuperclass();
+        return getGenericType((ParameterizedType) genType, 0);
+    }
+}

+ 35 - 37
workbenches/src/main/java/com/yingyang/workbenches/WorkbenchesActivity.kt

@@ -1,9 +1,11 @@
 package com.yingyang.workbenches
 
+import android.annotation.SuppressLint
 import androidx.recyclerview.widget.GridLayoutManager
 import com.alibaba.android.arouter.facade.annotation.Route
 import com.yingyang.workbenches.adapter.GameAdapter
 import com.yingyang.workbenches.databinding.ActivityWorkbenchesBinding
+import com.yingyang.workbenches.net.Record
 import com.yingyangfly.baselib.ext.setOnSingleClickListener
 import com.yingyangfly.baselib.ext.toast
 import com.yingyangfly.baselib.mvvm.BaseMVVMActivity
@@ -20,7 +22,7 @@ class WorkbenchesActivity : BaseMVVMActivity<ActivityWorkbenchesBinding, Workben
      * 第几页
      */
     private var page = 0
-    private var gameList = mutableListOf<String>()
+    private var gameList = mutableListOf<Record>()
 
     /**
      * 游戏adapter
@@ -28,42 +30,18 @@ class WorkbenchesActivity : BaseMVVMActivity<ActivityWorkbenchesBinding, Workben
     private val gameAdapter by lazy { GameAdapter() }
 
     override fun initViews() {
+        gameAdapter.setContext(this@WorkbenchesActivity)
         binding {
             swipeGame.setEnableRefresh(true)
             swipeGame.setEnableLoadMore(true)
-        }
-        binding {
             rvGame.layoutManager = GridLayoutManager(this@WorkbenchesActivity, 4)
             rvGame.adapter = gameAdapter
-            gameAdapter.setData(gameList)
-            gameAdapter.onGameImageClickListener = { bean, position ->
-                when (position) {
-                    0 -> {
-                        JumpUtil.jumpActivityWithUrl(
-                            RouterUrlCommon.load_web_view,
-                            "http://60.205.201.7/cocos/mobile/aoYouTaiKong/"
-                        )
-                    }
-                    1 -> {
-                        JumpUtil.jumpActivityWithUrl(
-                            RouterUrlCommon.load_web_view,
-                            "http://60.205.201.7/cocos/mobile/template/"
-                        )
-                    }
-                    2 -> {
-                        JumpUtil.jumpActivityWithUrl(
-                            RouterUrlCommon.load_web_view,
-                            "http://60.205.201.7/cocos/mobile/whacaMole/"
-                        )
-                    }
-                    else -> {
-                        JumpUtil.jumpActivityWithUrl(
-                            RouterUrlCommon.load_web_view,
-                            "http://60.205.201.7/cocos/mobile/template/"
-                        )
-                    }
-                }
-            }
+        }
+        gameAdapter.onGameImageClickListener = { bean, position ->
+            JumpUtil.jumpActivityWithUrl(
+                RouterUrlCommon.load_web_view,
+                bean.gameUrl
+            )
         }
     }
 
@@ -121,7 +99,6 @@ class WorkbenchesActivity : BaseMVVMActivity<ActivityWorkbenchesBinding, Workben
             swipeGame.setOnRefreshListener {
                 loadData(true)
             }
-
             swipeGame.setOnLoadMoreListener {
                 loadData(false)
             }
@@ -132,16 +109,37 @@ class WorkbenchesActivity : BaseMVVMActivity<ActivityWorkbenchesBinding, Workben
     /**
      * 加载游戏数据
      */
+    @SuppressLint("NotifyDataSetChanged")
     private fun loadData(isRefresh: Boolean) {
         if (isRefresh) {
-            page = 0
+            gameList.clear()
+            binding.swipeGame.resetNoMoreData()
+            page = 1
         } else {
             page++
         }
-        viewModel.loadData(page) { success: Unit ->
-            {
-
+        viewModel.loadData(page, fail = {
+            endRefresh()
+            "数据加载失败,请重试".toast()
+        }, success = {
+            endRefresh()
+            if (it.records.isNullOrEmpty().not()) {
+                gameList.addAll(it.records)
             }
+            gameAdapter.setData(gameList)
+            if (page >= it.pages) {
+                binding.swipeGame.finishLoadMoreWithNoMoreData()
+            }
+        })
+    }
+
+    /**
+     * 加载完成取消旋转框
+     */
+    private fun endRefresh() {
+        binding {
+            swipeGame.finishRefresh()
+            swipeGame.finishLoadMore()
         }
     }
 

+ 12 - 3
workbenches/src/main/java/com/yingyang/workbenches/WorkbenchesViewModel.kt

@@ -1,7 +1,11 @@
 package com.yingyang.workbenches
 
 import com.yingyang.workbenches.net.WORKBENCHES_API
+import com.yingyang.workbenches.net.WorkBenchesBean
+import com.yingyang.workbenches.net.WorkBenchesRequestBodyBean
 import com.yingyangfly.baselib.mvvm.BaseViewModel
+import com.yingyangfly.baselib.net.XUtils
+import com.yingyangfly.baselib.utils.GsonUtil
 
 /**
  * @author gold
@@ -12,11 +16,16 @@ import com.yingyangfly.baselib.mvvm.BaseViewModel
 class WorkbenchesViewModel : BaseViewModel() {
 
     fun loadData(
-        page: Int,
+        pageStr: Int,
         fail: ((msg: String) -> Unit)? = null,
-        success: ((success: Unit) -> Unit)? = null,
+        success: ((success: WorkBenchesBean) -> Unit)? = null,
     ) = launchFlow(false) {
-        WORKBENCHES_API.getGameList(page.toString(), "12")
+        val requestBean = WorkBenchesRequestBodyBean().apply {
+            page = pageStr.toString()
+            limit = "12"
+        }
+        val body = XUtils.createJson(GsonUtil.GsonString(requestBean))
+        WORKBENCHES_API.getGameList(body)
     }.runUI(
         success,
         fail

+ 15 - 3
workbenches/src/main/java/com/yingyang/workbenches/adapter/GameAdapter.kt

@@ -1,7 +1,10 @@
 package com.yingyang.workbenches.adapter
 
+import android.content.Context
+import com.bumptech.glide.Glide
 import com.yingyang.workbenches.R
 import com.yingyang.workbenches.databinding.ItemGameListBinding
+import com.yingyang.workbenches.net.Record
 import com.yingyangfly.baselib.adapter.BaseDataBindingAdapter
 import com.yingyangfly.baselib.ext.setOnSingleClickListener
 
@@ -9,15 +12,24 @@ import com.yingyangfly.baselib.ext.setOnSingleClickListener
  * 游戏adapter
  */
 class GameAdapter(override val layoutId: Int = R.layout.item_game_list) :
-    BaseDataBindingAdapter<String, ItemGameListBinding>() {
+    BaseDataBindingAdapter<Record, ItemGameListBinding>() {
+
+    var mContext: Context? = null
+
+    fun setContext(mContext: Context) {
+        this.mContext = mContext
+    }
 
     var onGameImageClickListener: ((
-        bean: String,
+        bean: Record,
         position: Int
     ) -> Unit)? = null
 
-    override fun onBindViewHolder(binding: ItemGameListBinding, item: String, position: Int) {
+    override fun onBindViewHolder(binding: ItemGameListBinding, item: Record, position: Int) {
         binding.data = item
+        if (mContext != null) {
+            Glide.with(mContext!!).load(item.gameUrl).into(binding.gameImage)
+        }
         binding.gameLayout.setOnSingleClickListener {
             onGameImageClickListener?.invoke(item, position)
         }

+ 37 - 0
workbenches/src/main/java/com/yingyang/workbenches/net/WorkBenchesBean.kt

@@ -0,0 +1,37 @@
+package com.yingyang.workbenches.net
+
+data class WorkBenchesBean(
+    val countId: Any,
+    val current: Int,
+    val maxLimit: Any,
+    val optimizeCountSql: Boolean,
+    val orders: List<Any>,
+    val pages: Int,
+    val records: List<Record>,
+    val searchCount: Boolean,
+    val size: Int,
+    val total: Int
+)
+
+data class Record(
+    val createBy: String,
+    val createTime: String,
+    val desn: String,//描述
+    val gameCode: String,//游戏编码
+    val gameDuration: Double,//游戏时长(分钟)
+    val gameLevel: Int,//游戏等级
+    val gameName: String,//游戏名字
+    val gameScore: Double,//游戏得分
+    val gameType: String,//游戏类型(字典维护)
+    val gameUrl: String,//游戏url
+    val gameVideoTitle: String,//游戏视频介绍
+    val gameVideoUrl: String,//	游戏视频介绍url
+    val id: String,
+    val limit: Int,
+    val orgCode: String,
+    val orgName: String,//机构名字
+    val page: Int,
+    val status: Int,//状态 0:正常 1:冻结 2:删除
+    val updateBy: String,
+    val updateTime: String
+)

+ 9 - 0
workbenches/src/main/java/com/yingyang/workbenches/net/WorkBenchesRequestBodyBean.kt

@@ -0,0 +1,9 @@
+package com.yingyang.workbenches.net
+
+/**
+ * 首页接口请求参数
+ */
+class WorkBenchesRequestBodyBean {
+    var page: String? = null//分页页码
+    var limit: String? = null//加载条数
+}

+ 4 - 6
workbenches/src/main/java/com/yingyang/workbenches/net/WorkbenchesApiService.kt

@@ -1,9 +1,8 @@
 package com.yingyang.workbenches.net
 
 import com.yingyangfly.baselib.net.BaseResp
-import retrofit2.http.GET
-import retrofit2.http.POST
-import retrofit2.http.Query
+import okhttp3.RequestBody
+import retrofit2.http.*
 
 interface WorkbenchesApiService {
 
@@ -12,7 +11,6 @@ interface WorkbenchesApiService {
      */
     @POST("game/list")
     suspend fun getGameList(
-        @Query("page") page: String,
-        @Query("limit") limit: String
-    ): BaseResp<Unit>
+        @Body requestBody: RequestBody
+    ): BaseResp<WorkBenchesBean>
 }

+ 1 - 1
workbenches/src/main/res/layout/activity_workbenches.xml

@@ -164,7 +164,7 @@
                 <androidx.recyclerview.widget.RecyclerView
                     android:id="@+id/rvGame"
                     android:layout_width="match_parent"
-                    android:layout_height="match_parent"
+                    android:layout_height="wrap_content"
                     tools:listitem="@layout/item_game_list" />
 
             </com.scwang.smartrefresh.layout.SmartRefreshLayout>

+ 4 - 4
workbenches/src/main/res/layout/item_game_list.xml

@@ -8,7 +8,7 @@
 
         <variable
             name="data"
-            type="java.lang.String" />
+            type="com.yingyang.workbenches.net.Record" />
     </data>
 
     <androidx.cardview.widget.CardView
@@ -19,9 +19,9 @@
         app:cardCornerRadius="@dimen/divider_20px">
 
         <ImageView
+            android:id="@+id/gameImage"
             android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:background="@mipmap/icon_game" />
+            android:layout_height="match_parent"/>
 
         <TextView
             android:layout_width="match_parent"
@@ -29,7 +29,7 @@
             android:layout_gravity="bottom|center"
             android:background="@drawable/bg_buttom_game"
             android:gravity="center"
-            android:text="@{data}"
+            android:text="@{data.gameName}"
             android:textColor="@color/color_FF821EFF"
             android:textSize="@dimen/divider_24px" />