为了用户体验用好,App在网络请求时通常都会显示个进度显示圈圈,提示用户耐心等待,最脍炙人口的莫过于登录啦。
接下来我们就通过Dialog来实现,然后在BaseActivity,BaseFragment中提供方法供调用
先看看自定义的dialog
package com.example.kbr.utils; import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.view.animation.Animation;
import android.widget.ImageView; /**
* Created by keranbin on 2017/12/19.
*/ public class LoadingDialog extends Dialog {
private ObjectAnimator objectAnimator = null;
private AppCompatImageView circle;
private long duration = 2000; public LoadingDialog(@NonNull Context context) {
super(context);
} public LoadingDialog(@NonNull Context context, int themeResId) {
super(context, themeResId);
} protected LoadingDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_loading);
} @Override
public void show() {
super.show();
startAnim();
setOnDismissListener(dialog -> {
endAnim();
});
} /**
* 启动动画
*/
private void startAnim() {
setCanceledOnTouchOutside(false);
circle = findViewById(R.id.loading);
objectAnimator = ObjectAnimator.ofFloat(circle, "rotation", 0.0f, 360.0f);
//设置动画时间
objectAnimator.setDuration(duration);
//设置动画重复次数,这里-1代表无限
objectAnimator.setRepeatCount(Animation.INFINITE);
//设置动画循环模式。
objectAnimator.setRepeatMode(ValueAnimator.RESTART);
objectAnimator.start();
} /**
* 结束动画
*/
private void endAnim() {
objectAnimator.end();
objectAnimator = null;
circle = null;
} }
布局也非常简单
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="0.4"
android:background="#000000"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="20dp"> <android.support.v7.widget.AppCompatImageView
android:id="@+id/loading"
android:layout_width="48dp"
android:layout_height="48dp"
app:srcCompat="@drawable/loading" />
</RelativeLayout>
BaseActivity,BaseFragment中提供方法
private LoadingDialog dialog; public void showLoading(){
if (dialog == null) {
dialog = new LoadingDialog(this);
}
dialog.show();
} public void clearLoading(){
if (dialog != null) {
dialog.dismiss();
}
}
在需要用到的地方调用即可
showLoading(); //执行网络耗时任务(这里时模拟)
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
clearLoading();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();