跳至主要內容

Android 自定义透明背景的 Dialog

JI,XIAOYONG...大约 1 分钟

简介

通过自定义 Dialog 类,使用 Style、AnimationDrawable 等实现一个透明背景的、带进度更新的弹窗。

主要涉及 Style 自定义以及 AnimationDrawable 的使用。

代码

  • 布局文件
<?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/dialog_bg">

    <ImageView
        android:id="@+id/image"
        android:layout_width="250dp"
        android:layout_height="250dp"
      />

</LinearLayout>
  • 资源文件

1)下载对应进度条的图片资源,放到 drawable 目录下

2)在 drawable 下新建 dialog_progress.xml

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <item
        android:drawable="@drawable/progress_1" //资源文件
        android:duration="300" /> //持续时间ms

    <item
        android:drawable="@drawable/progress_2"
        android:duration="300" />

  ...

</animation-list>

3)dialog 圆角背景(非必须)

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#6fb6d4" />
    <corners android:radius="500dp" />

</shape>

4)自定义 dialog 的 style

windowBackground使背景透明

backgroundDimEnabled则可以去除半透明遮罩效果

    <style name="diyDialogStyle" parent="@android:style/Theme.Dialog" >

        <item name="android:windowBackground">@android:color/transparent</item><!--背景透明-->
        <item name="android:backgroundDimEnabled">false</item><!--半透明,模糊-->

    </style>
  • DIYDialog.java

继承自Dialog.java ,并用构造函数调用initView()方法初始化 dialog 样式,有其他需求可以再自己实现。

//初始化 view、控件
View view = View.inflate(context, R.layout.layout_dialog, null);
ImageView imageView = view.findViewById(R.id.image);
imageView.setBackgroundResource(R.drawable.dialog_progress);
//填充布局
setContentView(view);
//实现动画
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();
animationDrawable.run();

源码

github 源码路径open in new window

文章标题:《Android 自定义透明背景的 Dialog》
本文作者: JI,XIAOYONG
发布时间: 2018/01/26 15:09:40 UTC+8
更新时间: 2023/12/30 16:17:02 UTC+8
written by human, not by AI
本文地址: https://jixiaoyong.github.io/blog/posts/f20627c9.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 许可协议。转载请注明出处!
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8