我正在使用改造库。如何在调用回调成功方法之前使用进度条?
public void getMovies() {
MovieClient.getWeather().movies(MovieClient.getRandomMovie(), new Callback<MovieRequest>() {
@Override
public void success(MovieRequest movieRequest, Response response) {
Picasso.with(getApplicationContext()).load(movieRequest.getPoster()).into(image);
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
答案 0 :(得分:20)
你可以这样使用它:
public void getMovies() {
ProgressDialog mProgressDialog = new ProgressDialog(this);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Loading...");
mProgressDialog.show();
MovieClient.getWeather().movies(MovieClient.getRandomMovie(), new Callback<MovieRequest>() {
@Override
public void success(MovieRequest movieRequest, Response response) {
Picasso.with(getApplicationContext()).load(movieRequest.getPoster()).into(image);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
@Override
public void failure(RetrofitError error) {
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
答案 1 :(得分:2)
您可以检查此方法util。 想法:创建包装器observable然后添加2个动作&#34; start&#34; &安培; &#34;精加工&#34;
public static <T> Observable<T> bindLoadingAction(final Runnable start, final Runnable finish, final Observable<T> source) {
final Observable<T> o = source.observeOn(AndroidSchedulers.mainThread());
return o.lift(new Observable.Operator<T, T>() {
@Override
public Subscriber<? super T> call(final Subscriber<? super T> child) {
return new Subscriber<T>() {
@Override
public void onStart() {
super.onStart();
if (start != null) {
new Handler(Looper.getMainLooper()).post(start::run);
}
child.onStart();
}
@Override
public void onCompleted() {
if (finish != null) {
finish.run();
}
child.onCompleted();
}
@Override
public void onError(Throwable e) {
if (finish != null) {
finish.run();
}
child.onError(e);
}
@Override
public void onNext(T t) {
if (finish != null) {
finish.run();
}
child.onNext(t);
}
};
}
});
}
使用:
bindLoadingAction(this::showLoadingView, this::hideLoadingView, YourRetrofitObservable);
(我使用Java 8语法。这个:: showLoadingView意味着引用当前类中的showLoadingView方法。)