Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義 ProgressDialog:兩種加載等待框的完整實現

編輯:關於 Android 程式設計

系統自帶的等待框樣式比較單一,項目裡往往需要一個帶自定義動畫和文案的版本。這裡整理兩種實現方式,可以按需挑選修改。

效果預覽

示例一:居中顯示的 frame 動畫加提示文字。

示例二:帶半透明背景與自定義旋轉動畫的等待框。

入口頁 MainActivity

只是兩個按鈕的跳轉:

package com.customwaitdialog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_customDialog1;
    private Button btn_customDialog2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_customDialog1 = (Button) findViewById(R.id.btn_customDialog1);
        btn_customDialog2 = (Button) findViewById(R.id.btn_customDialog2);
        btn_customDialog1.setOnClickListener(this);
        btn_customDialog2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_customDialog1:
                startActivity(new Intent(this, DialogActivity1.class));
                break;
            case R.id.btn_customDialog2:
                startActivity(new Intent(this, DialogActivity2.class));
                break;
            default:
                break;
        }
    }
}

示例一:DialogActivity1

用 AsyncTask 模擬一個耗時任務,在 onPreExecute 顯示等待框,在 onPostExecute 與 onCancelled 中關閉,順便兼顧 Activity 銷毀時的清理:

package com.customwaitdialog;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;

import com.dialogutil.CustomWaitDialog1;

public class DialogActivity1 extends Activity {

    private MainFrameTask mMainFrameTask;
    private CustomWaitDialog1 progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity1);
        mMainFrameTask = new MainFrameTask(this);
        mMainFrameTask.execute();
    }

    @Override
    protected void onDestroy() {
        stopProgressDialog();
        if (mMainFrameTask != null && !mMainFrameTask.isCancelled()) {
            mMainFrameTask.cancel(true);
        }
        super.onDestroy();
    }

    private void startProgressDialog() {
        if (progressDialog == null) {
            progressDialog = CustomWaitDialog1.createDialog(this);
            progressDialog.setMessage("正在加載中...");
        }
        progressDialog.show();
    }

    private void stopProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    public class MainFrameTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            startProgressDialog();
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            stopProgressDialog();
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Integer result) {
            stopProgressDialog();
        }
    }
}

核心:CustomWaitDialog1

繼承 Dialog,在窗口獲得焦點時啟動 frame 動畫:

package com.dialogutil;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.TextView;

import com.customwaitdialog.R;

public class CustomWaitDialog1 extends Dialog {

    private static CustomWaitDialog1 customProgressDialog;

    public CustomWaitDialog1(Context context) {
        super(context);
    }

    public CustomWaitDialog1(Context context, int theme) {
        super(context, theme);
    }

    public static CustomWaitDialog1 createDialog(Context context) {
        customProgressDialog = new CustomWaitDialog1(context, R.style.CustomProgressDialog);
        customProgressDialog.setCanceledOnTouchOutside(false);
        customProgressDialog.setContentView(R.layout.customprogressdialog);
        customProgressDialog.getWindow().getAttributes().gravity = Gravity.CENTER;
        return customProgressDialog;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (customProgressDialog == null) return;
        ImageView imageView = (ImageView) customProgressDialog
                .findViewById(R.id.loadingImageView);
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();
        animationDrawable.start();
    }

    public CustomWaitDialog1 setTitile(String strTitle) {
        return customProgressDialog;
    }

    public CustomWaitDialog1 setMessage(String strMessage) {
        TextView tvMsg = (TextView) customProgressDialog.findViewById(R.id.id_tv_loadingmsg);
        if (tvMsg != null) {
            tvMsg.setText(strMessage);
        }
        return customProgressDialog;
    }
}

樣式定義

關鍵是讓窗口透明、無邊框、無標題,並關閉背景變暗:

<resources>
    <style name="CustomDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
        <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    </style>

    <style name="CustomProgressDialog" parent="@style/CustomDialog">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
    </style>

    <style name="common_dialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>
</resources>

布局 customprogressdialog.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/loadingImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@anim/progress_round" />

    <TextView
        android:id="@+id/id_tv_loadingmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="20dp" />
</LinearLayout>

逐幀動畫 progress_round.xml,八幀循環:

<animation-list xmlns:android="https://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>

示例二:DialogActivity2

package com.customwaitdialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;

import com.dialogutil.CustomWaitDialog2;

public class DialogActivity2 extends Activity {

    private CustomWaitDialog2 waitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);

        waitDialog = new CustomWaitDialog2(this);
        waitDialog.show();
        waitDialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // 關閉時的收尾邏輯
            }
        });
    }
}

CustomWaitDialog2 的特點是使用 Alpha 動畫並自定義幕布濃度:

package com.dialogutil;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.customwaitdialog.R;

public class CustomWaitDialog2 {

    private final Context mContext;
    private final ImageView image;
    private final ImageView loading_pic_bigView;
    private final Dialog waitDialog;
    private final Animation mAnimation;

    public CustomWaitDialog2(Context mContext) {
        this.mContext = mContext;
        waitDialog = new Dialog(mContext, R.style.common_dialog);
        waitDialog.setContentView(R.layout.loading);
        waitDialog.setCanceledOnTouchOutside(false);

        /**
         * dimAmount 取值在 0.0f ~ 1.0f 之間:0 完全透明,1 全黑。
         * 若要讓背景變暗生效,必須同時加上 FLAG_DIM_BEHIND 標誌。
         */
        Window window = waitDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.dimAmount = 0.8f;
        window.setAttributes(lp);
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        loading_pic_bigView = (ImageView) waitDialog.findViewById(R.id.loading_pic_bigView);
        loading_pic_bigView.setAlpha(0.6f);
        image = (ImageView) waitDialog.findViewById(R.id.loading_pic_big);

        mAnimation = AnimationUtils.loadAnimation(mContext, R.anim.loading);
    }

    public void show() {
        image.startAnimation(mAnimation);
        waitDialog.show();
    }

    public void dismiss() {
        waitDialog.dismiss();
    }

    /** 網絡請求中斷時可以掛在此處做收尾 */
    public void setOnDismissListener(DialogInterface.OnDismissListener dismissListener) {
        waitDialog.setOnDismissListener(dismissListener);
    }
}

選型建議

示例一結構更輕,適合簡單的「全局加載中」提示;示例二對背景遮罩和動畫控制更細,適合需要突出等待狀態的場景。兩者的共同要點是:setCanceledOnTouchOutside(false) 防止誤觸關閉,以及在 Activity 銷毀時務必 dismiss,避免窗口泄漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved