如果遇到了很慢的处理过程,例如从网络下载文件等操作,我们通常会使用AsyncTask类来辅助完成,而同时为了给用户合理的等待操作,通常会在AsyncTask的onPreExecute方法中,添加一个ProgressDialog,告知用户等待,
系统自带的ProgressDialog有时不能满足我们的UI需要,这时需要我们自己来写,下面的内容就是实现了一个简单的带有旋转的ProgressDialog。
效果图如下:
打开后会一直在旋转(由于只是简单截图,所以四边有边角)
实现方法:
步骤一:定义一个布局文件,例如myalert.xml,定义要设计成的样式
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:background="@drawable/background" android:orientation="vertical" > <ImageView android:id="@+id/loading_img" android:src="@drawable/loadding_image" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
步骤二:定义一个ProgressDialog的子类,例如MyDialog,Override里面的onCreate方法
package xxxxxx.xxxxxxx; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnShowListener; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; public class MyDialog extends ProgressDialog { public MyDialog(Context context, int theme) { super(context, theme); } public MyDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myalert); setScreenBrightness(); this.setOnShowListener(new OnShowListener(){ @Override public void onShow(DialogInterface dialog) { ImageView image = (ImageView) MyDialog.this.findViewById(R.id.loading_img); Animation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f); anim.setRepeatCount(Animation.INFINITE); // 设置INFINITE,对应值-1,代表重复次数为无穷次 anim.setDuration(1000); // 设置该动画的持续时间,毫秒单位 anim.setInterpolator(new LinearInterpolator()); // 设置一个插入器,或叫补间器,用于完成从动画的一个起始到结束中间的补间部分 image.startAnimation(anim); } }); } private void setScreenBrightness() { WindowManager.LayoutParams lp = getWindow().getAttributes(); /** * 此处设置亮度值。dimAmount代表黑暗数量,也就是昏暗的多少,设置为0则代表完全明亮。 * 范围是0.0到1.0 */ lp.dimAmount = 0; } }
更新一下上面代码的错误:
重写setScreenBrightness方法,忘记重新设置回去了
private void setScreenBrightness() { Window window = getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); /** * 此处设置亮度值。dimAmount代表黑暗数量,也就是昏暗的多少,设置为0则代表完全明亮。 * 范围是0.0到1.0 */ lp.dimAmount = 0; window.setAttributes(lp); }
ProgressDialog pd = new MyDialog(Context); pd.show(); // 或者 // pd.dismiss();
至此,就完成了自定义ProgressDialog的工作。
欢迎大家拍砖指正!