为了用户体验用好,App在网络请求时通常都会显示个进度显示圈圈,提示用户耐心等待,最脍炙人口的莫过于登录啦。
接下来我们就通过Dialog来实现,然后在BaseActivity,BaseFragment中提供方法供调用
先看看自定义的dialog
1 package com.example.kbr.utils; 2 3 import android.animation.ObjectAnimator; 4 import android.animation.ValueAnimator; 5 import android.app.Dialog; 6 import android.content.Context; 7 import android.os.Bundle; 8 import android.support.annotation.NonNull; 9 import android.support.annotation.Nullable;10 import android.support.v7.widget.AppCompatImageView;11 import android.view.animation.Animation;12 import android.widget.ImageView;13 14 /**15 * Created by keranbin on 2017/12/19.16 */17 18 public class LoadingDialog extends Dialog {19 private ObjectAnimator objectAnimator = null;20 private AppCompatImageView circle;21 private long duration = 2000;22 23 public LoadingDialog(@NonNull Context context) {24 super(context);25 }26 27 public LoadingDialog(@NonNull Context context, int themeResId) {28 super(context, themeResId);29 }30 31 protected LoadingDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {32 super(context, cancelable, cancelListener);33 }34 35 @Override36 protected void onCreate(Bundle savedInstanceState) {37 super.onCreate(savedInstanceState);38 setContentView(R.layout.dialog_loading);39 }40 41 42 @Override43 public void show() {44 super.show();45 startAnim();46 setOnDismissListener(dialog -> {47 endAnim();48 });49 }50 51 /**52 * 启动动画53 */54 private void startAnim() {55 setCanceledOnTouchOutside(false);56 circle = findViewById(R.id.loading);57 objectAnimator = ObjectAnimator.ofFloat(circle, "rotation", 0.0f, 360.0f);58 //设置动画时间59 objectAnimator.setDuration(duration);60 //设置动画重复次数,这里-1代表无限61 objectAnimator.setRepeatCount(Animation.INFINITE);62 //设置动画循环模式。63 objectAnimator.setRepeatMode(ValueAnimator.RESTART);64 objectAnimator.start();65 }66 67 68 /**69 * 结束动画70 */71 private void endAnim() {72 objectAnimator.end();73 objectAnimator = null;74 circle = null;75 }76 77 }
布局也非常简单
1 214 15 20
BaseActivity,BaseFragment中提供方法
1 private LoadingDialog dialog; 2 3 4 public void showLoading(){ 5 if (dialog == null) { 6 dialog = new LoadingDialog(this); 7 } 8 dialog.show(); 9 }10 11 12 public void clearLoading(){13 if (dialog != null) {14 dialog.dismiss();15 }16 }
在需要用到的地方调用即可
1 showLoading(); 2 3 //执行网络耗时任务(这里时模拟) 4 new Thread(new Runnable() { 5 @Override 6 public void run() { 7 try { 8 Thread.sleep(10000); 9 clearLoading();10 } catch (InterruptedException e) {11 e.printStackTrace();12 }13 }14 }).start();