目标是这样的
用到的组件 AlertDialog
和 ProgressBar
先创建一个 AlertDialog 的布局
<?xml version="1.0" encoding="utf-8"?>
<!-- File: res/layout/dialog_loading.xml -->
<ProgressBar
style="?android:progressBarStyleLarge"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
接下来创建弹窗类,需要将背景设置为透明,否则背景很难看
package com.seliote.loadingdialog;
/**
* File: com/seliote/loadingdialog/LoadingDialog.java
*/
import android.content.Context;
import android.support.v7.app.AlertDialog;
public class LoadingDialog {
private Context mContext;
private AlertDialog mAlertDialog;
public LoadingDialog(Context aContext) {
mContext = aContext;
mAlertDialog = new AlertDialog.Builder(mContext)
.setView(R.layout.dialog_loading)
.create();
// Set AlertDialog background to transparent
mAlertDialog.getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
}
public void show() {
if (!mAlertDialog.isShowing()) {
mAlertDialog.show();
}
}
public void dismiss() {
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
}
效果
背景在弹窗后自动变暗,不怎么好看,修改一下
res/layout/styles.xml 中添加 style 标签
<!-- Disable background dim for AlertDialog -->
<style name="NoDimAlertDialog" parent="Theme.AppCompat.Dialog.Alert">
<item name="android:backgroundDimEnabled">false</item>
</style>
应用标签,LoadingDialog.java 中创建 AlertDialog 时使用自定义样式
mAlertDialog = new AlertDialog.Builder(mContext, R.style.NoDimAlertDialog)
效果
ok