关注
Android 中 ProgressBar 和 AlertDialog 的加载的基本使用

1. ProgressBar

1.1 默认效果

ProgressActivity

package com.example.hello;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.ProgressBar;

import com.example.hello.util.ToastUtil;

public class ProgressActivity extends AppCompatActivity {

    // 声明
    private ProgressBar pb4;
    private Button btnSimulation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);
        // 获取
        pb4 = findViewById(R.id.pb_4);
        // 获取
        btnSimulation = findViewById(R.id.btn_pb_simulation);
        btnSimulation.setOnClickListener(v -> {
            // 发送消息
            handler.sendEmptyMessage(0);
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (pb4.getProgress() < 100) {
                // 延迟执行 0.5s
                handler.postDelayed(runnable, 500);
            } else {
                ToastUtil.showShortToast(ProgressActivity.this, "加载完成");
            }
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            pb4.setProgress(pb4.getProgress() + 3);
            handler.sendEmptyMessage(0);
        }
    };

}

activity_progress

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="15dp"
    tools:context=".ProgressActivity">

    <ProgressBar
        android:id="@+id/pb_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="visible" />

    <ProgressBar
        android:id="@+id/pb_2"
        style="@android:style/Widget.ProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

    <ProgressBar
        android:id="@+id/pb_3"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:max="100"
        android:progress="10"
        android:secondaryProgress="30" />

    <ProgressBar
        android:id="@+id/pb_4"
        style="@android:style/Widget.Material.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:max="100"
        android:progress="10" />

    <Button
        android:id="@+id/btn_pb_simulation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_btn4"
        android:text="@string/pbSimulation"
        android:textColor="@color/white_up" />

</LinearLayout>

在这里插入图片描述

1.2 自定义样式

    <ProgressBar
        android:id="@+id/pb_5"
        style="@android:style/Widget.ProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:indeterminateDrawable="@drawable/bg_progress" />

    <ProgressBar
        android:id="@+id/pb_6"
        style="@style/MyProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

bg_progress 文件中 @drawable/progress 是一个静止的加载照片

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/progress"
    android:pivotX="50%"
    android:pivotY="50%">

</animated-rotate>

@style/MyProgressBarvalues 下的 styles.xml 文件中.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="MyProgressBar">
        <item name="android:indeterminateOnly">true</item>
        <item name="android:indeterminateDrawable">@drawable/bg_progress</item>
        <item name="android:indeterminateBehavior">repeat</item>
        <item name="android:indeterminateDuration">3500</item>
        <item name="android:minWidth">48dip</item>
        <item name="android:maxWidth">48dip</item>
        <item name="android:minHeight">48dip</item>
        <item name="android:maxHeight">48dip</item>
        <item name="android:mirrorForRtl">false</item>
    </style>

</resources>

在这里插入图片描述

2. AlertDialog 的加载

ProgressDialog 被弃用了. 所以没有转动加载的动漫效果. 添加需要自定义.

2.1 默认效果

    <Button
        android:id="@+id/btn_pb_dialog_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@drawable/bg_btn2"
        android:text="@string/pbDialog1" />
package com.example.hello;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.ProgressBar;

import com.example.hello.util.ToastUtil;

public class ProgressActivity extends AppCompatActivity {

    // 声明
    private ProgressBar pb4;
    private Button btnSimulation, pbDialog1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);
        // 获取
        pb4 = findViewById(R.id.pb_4);
        // 获取
        btnSimulation = findViewById(R.id.btn_pb_simulation);
        btnSimulation.setOnClickListener(v -> {
            // 发送消息
            handler.sendEmptyMessage(0);
        });
        // 获取
        pbDialog1 = findViewById(R.id.btn_pb_dialog_1);
        pbDialog1.setOnClickListener(v -> {
            LoadingDialog loadingDialog = new LoadingDialog(ProgressActivity.this);
            loadingDialog.setTitle("提示");
            loadingDialog.setMessage("正在加载...");
            loadingDialog.setOnCancelListener(dialog -> {
                ToastUtil.showShortToast(ProgressActivity.this, "cancel...");
            });
            loadingDialog.show();
        });
    }

    /**
     * AlertDialog 的加载
     */
    static class LoadingDialog extends AlertDialog {

        protected LoadingDialog(Context context) {
            super(context);
        }

        protected LoadingDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        protected LoadingDialog(Context context, int themeResId) {
            super(context, themeResId);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (pb4.getProgress() < 100) {
                // 延迟执行 0.5s
                handler.postDelayed(runnable, 500);
            } else {
                ToastUtil.showShortToast(ProgressActivity.this, "加载完成");
            }
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            pb4.setProgress(pb4.getProgress() + 3);
            handler.sendEmptyMessage(0);
        }
    };

}

在这里插入图片描述
在这里插入图片描述

2.2 自定义样式

ProgressActivity

package com.example.hello;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.example.hello.util.ToastUtil;
import com.example.hello.widget.CustomDialog;

public class ProgressActivity extends AppCompatActivity {

    // 声明
    private ProgressBar pb4;
    private Button btnSimulation, pbDialog1, pbDialog2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);
        // 获取
        pb4 = findViewById(R.id.pb_4);
        // 获取
        btnSimulation = findViewById(R.id.btn_pb_simulation);
        btnSimulation.setOnClickListener(v -> {
            // 发送消息
            handler.sendEmptyMessage(0);
        });
        // 获取
        pbDialog1 = findViewById(R.id.btn_pb_dialog_1);
        pbDialog1.setOnClickListener(v -> {
            LoadingDialog loadingDialog = new LoadingDialog(ProgressActivity.this);
            loadingDialog.setTitle("提示");
            loadingDialog.setMessage("正在加载...");
            loadingDialog.setOnCancelListener(dialog -> {
                ToastUtil.showShortToast(ProgressActivity.this, "cancel...");
            });
            loadingDialog.show();
        });
        pbDialog2 = findViewById(R.id.btn_pb_dialog_2);
        pbDialog2.setOnClickListener(v -> {
            CustomDialog customDialog = new CustomDialog(ProgressActivity.this, R.style.CustomDialog);
            customDialog.setTitle("提示").setMessage("确定删除此项?").setCancel("取消", dialog -> {
                ToastUtil.showShortToast(ProgressActivity.this, "取消成功");
            }).setConfirm("确定", dialog -> {
                ToastUtil.showShortToast(ProgressActivity.this, "删除成功");
            }).setCustomCancelable(false).show();
        });
    }

    /**
     * AlertDialog 的加载
     */
    static class LoadingDialog extends AlertDialog {

        protected LoadingDialog(Context context) {
            super(context);
        }

        protected LoadingDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        protected LoadingDialog(Context context, int themeResId) {
            super(context, themeResId);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (pb4.getProgress() < 100) {
                // 延迟执行 0.5s
                handler.postDelayed(runnable, 500);
            } else {
                ToastUtil.showShortToast(ProgressActivity.this, "加载完成");
            }
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            pb4.setProgress(pb4.getProgress() + 3);
            handler.sendEmptyMessage(0);
        }
    };

}

CustomDialog 文件是自定义的 Dialog.

package com.example.hello.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.hello.R;

public class CustomDialog extends Dialog implements View.OnClickListener {

    private TextView tvTitle, tvMassage, tvCancel, tvConfirm;
    private String title, message, cancel, confirm;

    private IOnCancelListener cancelListener;
    private IOnConfirmListener confirmListener;

    public CustomDialog setTitle(String title) {
        this.title = title;
        return this;
    }

    public CustomDialog setMessage(String message) {
        this.message = message;
        return this;
    }

    public CustomDialog setCancel(String cancel, IOnCancelListener listener) {
        this.cancel = cancel;
        this.cancelListener = listener;
        return this;
    }

    public CustomDialog setConfirm(String confirm, IOnConfirmListener listener) {
        this.confirm = confirm;
        this.confirmListener = listener;
        return this;
    }

    public CustomDialog(@NonNull Context context) {
        super(context);
    }

    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected CustomDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    /**
     * 自定义 setCancelable 方法返回 CustomDialog
     *
     * @param flag 是否点击周围消失
     * @return CustomDialog
     */
    public CustomDialog setCustomCancelable(boolean flag) {
        this.setCancelable(false);
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom);
        // 设置宽度
        WindowManager width = getWindow().getWindowManager();
        Display defaultDisplay = width.getDefaultDisplay();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        Point size = new Point();
        defaultDisplay.getSize(size);
        // 设置宽度为当前手机屏幕的 0.8 倍
        layoutParams.width = (int) (size.x * 0.8);
        getWindow().setAttributes(layoutParams);
        // 获取内容
        tvTitle = findViewById(R.id.custom_tv_title);
        tvMassage = findViewById(R.id.custom_tv_message);
        tvCancel = findViewById(R.id.custom_tv_cancel);
        tvConfirm = findViewById(R.id.custom_tv_confirm);
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (!TextUtils.isEmpty(message)) {
            tvMassage.setText(message);
        }
        if (!TextUtils.isEmpty(cancel)) {
            tvCancel.setText(cancel);
        }
        if (!TextUtils.isEmpty(confirm)) {
            tvConfirm.setText(confirm);
        }
        tvCancel.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.custom_tv_cancel:
                if (cancelListener != null) {
                    cancelListener.OnCancel(this);
                }
                dismiss();
                break;
            case R.id.custom_tv_confirm:
                if (confirmListener != null) {
                    confirmListener.OnConfirm(this);
                }
                dismiss();
                break;
        }
    }

    /**
     * 取消的监听事件
     */
    public interface IOnCancelListener {
        void OnCancel(CustomDialog dialog);
    }

    /**
     * 确定的监听事件
     */
    public interface IOnConfirmListener {
        void OnConfirm(CustomDialog dialog);
    }
}

activity_custom 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/custom_tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="@string/tips"
        android:textColor="@color/black"
        android:textSize="25sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/custom_tv_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:layout_marginBottom="25dp"
        android:gravity="center"
        android:text="@string/isDelete"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/black_low" />

    <LinearLayout
        android:id="@+id/custom_ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/custom_tv_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/white_up"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/cancel"
            android:textColor="@color/purple_700"
            android:textSize="20sp" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/black_low" />

        <TextView
            android:id="@+id/custom_tv_confirm"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/white_up"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/confirm"
            android:textColor="@color/orange_low"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>

R.style.CustomDialog 是 values 下 styles 里内容.

    <style name="CustomDialog" parent="android:Theme.Holo.Light.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:background">@color/teal_200</item>
    </style>

在这里插入图片描述

在这里插入图片描述

转载自CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/YKenan/article/details/113079246

文章分类Android

评论

赞0

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--