Android 中 ProgressBar 和 ProgressDialog 的基本使用

    • 1. ProgressBar
      • 1.1 默认效果
      • 1.2 自定义样式
    • 2. AlertDialog 的加载
      • 2.1 默认效果
      • 2.2 自定义样式

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">        "android:indeterminateOnly">true        "android:indeterminateDrawable">@drawable/bg_progress        "android:indeterminateBehavior">repeat        "android:indeterminateDuration">3500        "android:minWidth">48dip        "android:maxWidth">48dip        "android:minHeight">48dip        "android:maxHeight">48dip        "android:mirrorForRtl">false    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">        "android:windowNoTitle">true        "android:windowIsFloating">true        "android:background">@color/teal_200    style>

更多相关文章

  1. Android获取本机电话号码的简单方法
  2. Android5.x+ 格式化外部存储(u盘, sdcard)的方法
  3. Android获取设备ID号
  4. androidx.core.widget.NestedScrollView 内容显示不全
  5. android锁屏唤醒并解锁屏幕
  6. android 时间获取以及时间格式化
  7. 让应用程序不被任务管理器杀死...(获取系统权限)
  8. android EditText 默认情况下不获取焦点(不弹出输入框)
  9. android GridView 去掉自带点击边框效果和禁止上下滑动

随机推荐

  1. Android(安卓)Studio 提示与技巧(官方文档
  2. Android中px, dp, sp单位转换
  3. android 顶部Tab实现及原理
  4. 关于houdini技术和android x86平台兼容性
  5. 学习OpenGL ES for Android(十三)— 投光物
  6. 一场针对手机底层的新圈地运动(程苓峰)
  7. Android老矣,尚能饭否?即将步入2020年的你
  8. Android(安卓)主流开源框架(二)OkHttp 使用
  9. 安装Android(安卓)studio的详细步骤
  10. 在Android中为啥建议你用Message.obtain(