在Android应用中,经常会用到网络传输,不可避免的是,在传输过程中会受网络的影响,在等待服务器的响应的时候,用户体验就至关重要了,所以应该在等待的过程中,给应用加上一个加载框,这样用户体验就大大提升。那么该如何实现自定义的加载框呢?
第一步,准备好加载动画的素材,然后创建progress_loading.xml文件,代码与效果如下
<?xml version="1.0" encoding="utf-8"?>
<animation-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/progress_1" android:duration="200"/>
<item android:drawable="@drawable/progress_2" android:duration="200"/>
<item android:drawable="@drawable/progress_3" android:duration="200"/>
<item android:drawable="@drawable/progress_4" android:duration="200"/>
<item android:drawable="@drawable/progress_5" android:duration="200"/>
<item android:drawable="@drawable/progress_6" android:duration="200"/>
<item android:drawable="@drawable/progress_7" android:duration="200"/>
<item android:drawable="@drawable/progress_8" android:duration="200"/>
</animation-list>
第二步,创建弹窗dialog_loading.xml,在ImageView标签中加入progress_loading.xml文件,其他弹窗样式根据自己的需求来该,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/loading_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:paddingTop="10dp"
android:src="@drawable/progress_loading"/>
<TextView
android:id="@+id/loading_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/loading_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="努力加载中..."
android:textColor="#999999"
android:textSize="12dp" />
</RelativeLayout>
第三步,实现创建一个LoadingDialog的类,然后继承弹窗继承类,代码如下:
/**
* 加载中动画弹窗
*/
public class LoadingDialog extends Dialog {
private String text;//提示
private AnimationDrawable animationDrawable;
public LoadingDialog(Context context) {
super(context, R.style.loadingDialog);
}
public LoadingDialog(Context context, String text) {
super(context, R.style.loadingDialog); //这里设置了Dialog的Style让其背景为透明的,并且没有title,具体代码就不贴了
this.text = text;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_loading);
//按空白处不能取消动画
setCanceledOnTouchOutside(false);
if (text!= null){
TextView textView = (TextView) findViewById(R.id.loading_text);
textView.setText(text);
}
ImageView progressImageView = (ImageView) findViewById(R.id.loading_image); //在ImageView上使用帧动画
animationDrawable = (AnimationDrawable) getContext().getResources().getDrawable(R.drawable.progress_loading); //帧动画的初始化
progressImageView.setImageDrawable(animationDrawable); //将动画设置在ImageView上
}
/**
* 开始帧动画
*/
@Override
protected void onStart() {
animationDrawable.start();
super.onStart();
}
/**
* 停止帧动画
*/
@Override
protected void onStop() {
animationDrawable.stop();
super.onStop();
}
}
第四步,直接在相关页面实例化LoadingDialog类,然后在网络请求的代码前调用实例化对象的show()方法,网络请求代码后调用实例化对象的hide()方法即可;
最终效果如下: