Skip to content

Commit

Permalink
修改加载图片回调机制
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfusheng committed Jun 15, 2018
1 parent ae56b21 commit b9161cf
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 39 deletions.
Binary file modified .idea/caches/build_file_checksums.ser
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
Expand All @@ -22,7 +23,7 @@
import java.lang.ref.WeakReference;

/**
* Created by sunfusheng on 2017/6/6.
* @author by sunfusheng on 2017/6/6.
*/
public class GlideImageLoader {

Expand Down Expand Up @@ -82,16 +83,16 @@ protected GlideImageLoader loadImage(Object obj, @DrawableRes int placeholder, T
glideRequest = glideRequest.transform(transformation);
}

glideRequest = glideRequest.diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true);

glideRequest.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
ProgressManager.removeListener(url);
return false;
}

@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
ProgressManager.removeListener(url);
return false;
}
}).into(getImageView());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
*/
public class GlideImageView extends ImageView {

private float pressedAlpha = 0.4f;
private float unableAlpha = 0.3f;
private GlideImageLoader imageLoader;

public GlideImageView(Context context) {
Expand Down Expand Up @@ -51,14 +53,14 @@ public void load(String url, @DrawableRes int placeholder) {
load(url, placeholder, null);
}

public void load(String url, @DrawableRes int placeholder, OnProgressListener onProgressListener) {
load(url, placeholder, null, onProgressListener);
}

public void load(String url, @DrawableRes int placeholder, int radius) {
load(url, placeholder, radius, null);
}

public void load(String url, @DrawableRes int placeholder, OnProgressListener onProgressListener) {
load(url, placeholder, null, onProgressListener);
}

public void load(String url, @DrawableRes int placeholder, int radius, OnProgressListener onProgressListener) {
load(url, placeholder, new RadiusTransformation(getContext(), radius), onProgressListener);
}
Expand Down Expand Up @@ -90,4 +92,16 @@ public void loadDrawable(@DrawableRes int resId, @DrawableRes int placeholder) {
public void loadDrawable(@DrawableRes int resId, @DrawableRes int placeholder, @NonNull Transformation<Bitmap> transformation) {
getImageLoader().load(resId, placeholder, transformation);
}

@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (isPressed()) {
setAlpha(pressedAlpha);
} else if (!isEnabled()) {
setAlpha(unableAlpha);
} else {
setAlpha(1.0f);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.sunfusheng.glideimageview.progress;

import android.text.TextUtils;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -16,7 +16,7 @@
*/
public class ProgressManager {

private static Map<String, WeakReference<OnProgressListener>> listenersMap = Collections.synchronizedMap(new HashMap<>());
private static Map<String, OnProgressListener> listenersMap = Collections.synchronizedMap(new HashMap<>());
private static OkHttpClient okHttpClient;

private ProgressManager() {
Expand All @@ -29,22 +29,48 @@ public static OkHttpClient getOkHttpClient() {
Request request = chain.request();
Response response = chain.proceed(request);
return response.newBuilder()
.body(new ProgressResponseBody(request.url().toString(), listenersMap, response.body()))
.body(new ProgressResponseBody(request.url().toString(), LISTENER, response.body()))
.build();
}).build();
})
.build();
}
return okHttpClient;
}

private static final ProgressResponseBody.InternalProgressListener LISTENER = (url, bytesRead, totalBytes) -> {
OnProgressListener onProgressListener = getProgressListener(url);
if (onProgressListener != null) {
int percentage = (int) ((bytesRead * 1f / totalBytes) * 100f);
onProgressListener.onProgress(percentage, bytesRead, totalBytes);
if (percentage >= 100) {
removeListener(url);
}
}
};

public static void addListener(String url, OnProgressListener listener) {
if (!TextUtils.isEmpty(url) && listener != null) {
listenersMap.put(url, new WeakReference<>(listener));
Log.d("--->", "【addListener】url: " + url + "\nlistener: " + listener);
listenersMap.put(url, listener);
}
}

public static void removeListener(String url) {
Log.d("--->", "【removeListener】url: " + url);
if (!TextUtils.isEmpty(url)) {
listenersMap.remove(url);
}
}

public static OnProgressListener getProgressListener(String url) {
if (TextUtils.isEmpty(url) || listenersMap == null || listenersMap.size() == 0) {
return null;
}

OnProgressListener listenerWeakReference = listenersMap.get(url);
if (listenerWeakReference != null) {
return listenerWeakReference;
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
Expand All @@ -25,14 +22,14 @@ public class ProgressResponseBody extends ResponseBody {
private static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

private String url;
private Map<String, WeakReference<OnProgressListener>> listenersMap;
private ProgressResponseBody.InternalProgressListener internalProgressListener;

private ResponseBody responseBody;
private BufferedSource bufferedSource;

ProgressResponseBody(String url, Map<String, WeakReference<OnProgressListener>> listenersMap, ResponseBody responseBody) {
ProgressResponseBody(String url, ProgressResponseBody.InternalProgressListener internalProgressListener, ResponseBody responseBody) {
this.url = url;
this.listenersMap = listenersMap;
this.internalProgressListener = internalProgressListener;
this.responseBody = responseBody;
}

Expand Down Expand Up @@ -64,26 +61,16 @@ public long read(@NonNull Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
totalBytesRead += (bytesRead == -1) ? 0 : bytesRead;

OnProgressListener onProgressListener = getProgressListener();
if (onProgressListener != null && lastTotalBytesRead != totalBytesRead) {
if (internalProgressListener != null && lastTotalBytesRead != totalBytesRead) {
lastTotalBytesRead = totalBytesRead;
int percentage = (int) ((bytesRead * 1f / contentLength()) * 100f);
mainThreadHandler.post(() -> onProgressListener.onProgress(percentage, totalBytesRead, contentLength()));
mainThreadHandler.post(() -> internalProgressListener.onProgress(url, totalBytesRead, contentLength()));
}
return bytesRead;
}
};
}

private OnProgressListener getProgressListener() {
if (TextUtils.isEmpty(url) || listenersMap == null || listenersMap.size() == 0) {
return null;
}

WeakReference<OnProgressListener> listenerWeakReference = listenersMap.get(url);
if (listenerWeakReference != null) {
return listenerWeakReference.get();
}
return null;
interface InternalProgressListener {
void onProgress(String url, long bytesRead, long totalBytes);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.sunfusheng.glideimageview.GlideImageView;
import com.sunfusheng.glideimageview.progress.CircleProgressView;
import com.sunfusheng.glideimageview.sample.about.AboutActivity;

/**
* Created by sunfusheng on 2017/6/3.
* @author by sunfusheng on 2017/6/3.
*/
public class MainActivity extends BaseActivity {

Expand Down Expand Up @@ -81,9 +82,7 @@ private void line1() {
image11.load(url1);
image12.loadCircle(url1);
image13.load(url2, R.color.placeholder);
image14.load(url2, R.color.placeholder, 10, (percentage, bytesRead, totalBytes) -> {
Log.d("--->", "percentage: " + percentage + " totalBytes: " + totalBytes + " bytesRead: " + bytesRead);
});
image14.load(url2, R.color.placeholder, 10);
}

private void line2() {
Expand All @@ -94,7 +93,25 @@ private void line2() {
}

private void line3() {
image31.load(girl, R.color.placeholder, (percentage, bytesRead, totalBytes) -> {
Log.d("--->", "【load girl】 percentage: " + percentage + " totalBytes: " + totalBytes + " bytesRead: " + bytesRead);
if (percentage >= 100) {
progressView1.setVisibility(View.GONE);
} else {
progressView1.setVisibility(View.VISIBLE);
progressView1.setProgress(percentage);
}
});

image32.load(cat, R.color.placeholder, (percentage, bytesRead, totalBytes) -> {
Log.d("--->", "【load cat】percentage: " + percentage + " totalBytes: " + totalBytes + " bytesRead: " + bytesRead);
if (percentage >= 100) {
progressView2.setVisibility(View.GONE);
} else {
progressView2.setVisibility(View.VISIBLE);
progressView2.setProgress(percentage);
}
});
}

// Intent intent = new Intent(MainActivity.this, SingleImageActivity.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.sunfusheng.glideimageview.sample;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
Expand Down Expand Up @@ -40,18 +41,18 @@ class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewH
this.list = list;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_right_image, viewGroup, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
NewsModel entity = list.get(position);
viewHolder.tvTitle.setText(entity.getTitle());
viewHolder.imageView.load(entity.getImage_url(), R.color.placeholder);

viewHolder.llRootView.setOnClickListener(v -> Toast.makeText(mContext, entity.getTitle(), Toast.LENGTH_SHORT).show());
}

Expand Down
2 changes: 2 additions & 0 deletions Sample/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
android:id="@+id/image31"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:transitionName="@string/transitional_image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
Expand Down Expand Up @@ -143,6 +144,7 @@
android:id="@+id/image32"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:transitionName="@string/transitional_image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
Expand Down
1 change: 1 addition & 0 deletions Sample/src/main/res/layout/item_right_image.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
android:id="@+id/giv"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="16:9"
app:layout_constraintLeft_toLeftOf="parent"
Expand Down

0 comments on commit b9161cf

Please sign in to comment.