46.Android 自己定义Dialog

46.Android 自己定义Dialog

  • Android 自己定义Dialog

    • 前言
    • 提示Dialog
    • 提示Dialog 效果图
    • 菜单Dialog
    • 菜单Dialog 效果图
    • DialogActivity

前言

提供两套自己定义Dialog模板

  • 第一种。提示Dialog,有消失时间。
  • 另外一种,菜单Dialog,用于用户交互。

提示Dialog

CustomDialog

public class CustomDialog extends Dialog {

    private TextView dialogTV;

    private static final long DEFAULT_DURATION = 1000L;
    private static final String DEFAULT_CONTENT = "";

    private long duration;
    private String content;

    private DialogCallback callback;

    public CustomDialog(Context context) {
        super(context, R.style.custom_dialog);
        this.initViews(context);
    }

    /**
     * Creates a dialog window that uses a custom dialog style.
     * <p/>
     * The supplied {@code context} is used to obtain the window manager and
     * base theme used to present the dialog.
     * <p/>
     * The supplied {@code theme} is applied on top of the context‘s theme. See
     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">
     * Style and Theme Resources</a> for more information about defining and
     * using styles.
     *
     * @param context    the context in which the dialog should run
     * @param themeResId a style resource describing the theme to use for the
     *                   window, or {@code 0} to use the default dialog theme
     */
    public CustomDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.initViews(context);
    }

    public CustomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.initViews(context);
    }

    private void initViews(Context context) {
        this.setContentView(R.layout.dialog_custom);
        this.dialogTV = (TextView) this.findViewById(R.id.custom_dialog_tv);
    }

    @Override
    public void show() {
        super.show();
        this.dialogTV.setText(TextUtils.isEmpty(this.content) ? DEFAULT_CONTENT : this.content);
        long showDuration = this.duration > 0L ? this.duration : DEFAULT_DURATION;
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (CustomDialog.this.isShowing()) {
                    CustomDialog.this.dismiss();
                    if (CustomDialog.this.callback != null) CustomDialog.this.callback.onDismiss();
                }
            }
        }, showDuration);
    }

    public void setTextDrawable(Drawable drawable) {
        if (drawable == null) return;
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        this.dialogTV.setCompoundDrawables(drawable, null, null, null);
    }

    public interface DialogCallback {
        void onDismiss();
    }

    public static class DialogBuilder {
        private static String contextHashCode;
        private static CustomDialog dialog;
        public static DialogBuilder ourInstance;

        public static DialogBuilder getInstance(Context context) {
            if (ourInstance == null) ourInstance = new DialogBuilder();
            String hashCode = String.valueOf(context.hashCode());
            /**
             * 不同一个Activity
             */
            if (!hashCode.equals(String.valueOf(contextHashCode))) {
                contextHashCode = hashCode;
                dialog = new CustomDialog(context);
            }
            return ourInstance;
        }

        public DialogBuilder setDuration(long duration) {
            dialog.duration = duration;
            return this;
        }

        public DialogBuilder setContent(String content) {
            dialog.content = content;
            return this;
        }

        public DialogBuilder setDrawable(Drawable drawable) {
            dialog.setTextDrawable(drawable);
            return this;
        }

        public DialogBuilder setCallback(DialogCallback callback) {
            dialog.callback = callback;
            return this;
        }

        public DialogBuilder setCanceledOnTouchOutside(boolean cancel) {
            dialog.setCanceledOnTouchOutside(cancel);
            return this;
        }

        public CustomDialog getDialog() {
            return dialog;
        }

    }

}

dialog_custom.xml

<?

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:gravity="center">

    <TextView
        android:id="@+id/custom_dialog_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_dialog_custom_tv"
        android:drawableLeft="@mipmap/dialog_custom_tv_drawable"
        android:drawablePadding="5dp"
        android:drawableStart="@mipmap/dialog_custom_tv_drawable"
        android:gravity="center"
        android:text="成功"
        android:textColor="#ff666666"
        android:textSize="15sp" />
</LinearLayout>

R.style.custom_dialog

<style name="custom_dialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@color/transparent</item>
    <item name="android:windowIsTranslucent">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">true</item>
</style>

提示Dialog 效果图


菜单Dialog

MenuDialog

public class MenuDialog extends Dialog {

    private TextView caseTV;
    private TextView helpTV;

    public MenuDialog(Context context) {
        super(context, R.style.menu_dialog);
        this.initViews(context);
    }

    /**
     * Creates a dialog window that uses a custom dialog style.
     * <p/>
     * The supplied {@code context} is used to obtain the window manager and
     * base theme used to present the dialog.
     * <p/>
     * The supplied {@code theme} is applied on top of the context‘s theme. See
     * <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">
     * Style and Theme Resources</a> for more information about defining and
     * using styles.
     *
     * @param context    the context in which the dialog should run
     * @param themeResId a style resource describing the theme to use for the
     *                   window, or {@code 0} to use the default dialog theme
     */
    public MenuDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.initViews(context);
    }

    public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.initViews(context);
    }

    private void initViews(Context context) {
        this.setContentView(R.layout.dialog_menu);
        this.caseTV = (TextView) this.findViewById(R.id.dialog_menu_case_tv);
        this.helpTV = (TextView) this.findViewById(R.id.dialog_menu_help_tv);
    }

    public void setTextDrawable(Drawable drawable) {
        if (drawable == null) return;
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    }

    public static class DialogBuilder {
        private static String contextHashCode;
        private static MenuDialog dialog;
        public static DialogBuilder ourInstance;

        public static DialogBuilder getInstance(Context context) {
            if (ourInstance == null) ourInstance = new DialogBuilder();
            String hashCode = String.valueOf(context.hashCode());
            /**
             * 不同一个Activity
             */
            if (!hashCode.equals(String.valueOf(contextHashCode))) {
                contextHashCode = hashCode;
                dialog = new MenuDialog(context);
            }
            return ourInstance;
        }

        public DialogBuilder setCaseListenser(View.OnClickListener listener) {
            dialog.caseTV.setOnClickListener(listener);
            return this;
        }

        public DialogBuilder setHelpListener(View.OnClickListener listener) {
            dialog.helpTV.setOnClickListener(listener);
            return this;
        }

        public DialogBuilder setCanceledOnTouchOutside(boolean cancel) {
            dialog.setCanceledOnTouchOutside(cancel);
            return this;
        }

        public MenuDialog getDialog() {
            return dialog;
        }

    }

}

dialog_menu.xml

<?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:layout_gravity="center"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/dialog_menu_case_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_dialog_menu_item"
        android:drawablePadding="13dp"
        android:drawableTop="@mipmap/dialog_menu_case"
        android:paddingBottom="13.5dp"
        android:paddingEnd="36dp"
        android:paddingLeft="36dp"
        android:paddingRight="36dp"
        android:paddingTop="20dp"
        android:gravity="center_horizontal"
        android:text="Case"
        android:textColor="#ff666666"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/dialog_menu_help_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:background="@drawable/bg_dialog_menu_item"
        android:drawablePadding="13dp"
        android:drawableTop="@mipmap/dialog_menu_help"
        android:gravity="center_horizontal"
        android:paddingBottom="13.5dp"
        android:paddingEnd="36dp"
        android:paddingLeft="36dp"
        android:paddingRight="36dp"
        android:paddingTop="20dp"
        android:text="Help"
        android:textColor="#ff666666"
        android:textSize="14sp" />

</LinearLayout>

R.style.menu_dialog

<style name="menu_dialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@color/transparent</item>
    <item name="android:windowIsTranslucent">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">true</item>
</style>

菜单Dialog 效果图


DialogActivity

public class DialogActivity extends AppCompatActivity implements View.OnClickListener {

    private MenuDialog menuDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_dialog);
        this.menuDialog = MenuDialog.DialogBuilder.getInstance(this)
                .setCaseListenser(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(DialogActivity.this, "case", Toast.LENGTH_SHORT).show();
                        DialogActivity.this.menuDialog.dismiss();
                    }
                })
                .setHelpListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(DialogActivity.this, "Help", Toast.LENGTH_SHORT).show();
                        DialogActivity.this.menuDialog.dismiss();
                    }
                })
                .getDialog();
        this.initListeners();
    }

    private void initListeners() {
        this.findViewById(R.id.dialog_custom).setOnClickListener(this);
        this.findViewById(R.id.dialog_menu).setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_custom:
                CustomDialog.DialogBuilder.getInstance(this)
                        .setDuration(2000L)
                        .setContent("CustomDialog")
                        .setCanceledOnTouchOutside(false)
                        .setCallback(new CustomDialog.DialogCallback() {
                            @Override
                            public void onDismiss() {
                                Toast.makeText(DialogActivity.this, "CustomDialog dismiss", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .getDialog()
                        .show();
                break;
            case R.id.dialog_menu:
                this.menuDialog.show();
                break;
        }
    }
}

activity_dialog.xml

<?

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"
    android:padding="26dp">

    <TextView
        android:id="@+id/dialog_custom"
        style="@style/TextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CustomDialog" />

    <TextView
        android:id="@+id/dialog_menu"
        style="@style/TextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MenuDialog" />

</LinearLayout>
时间: 2024-08-04 18:18:27

46.Android 自己定义Dialog的相关文章

android 自己定义dialog并实现失去焦点(背景透明)的功能

前言:因为在项目中须要用到更新显示动画的需求,所以想到了dialog,自己定义dialog不难.网上教程非常多,可是在实现dialog背景透明的需求时,遇到了一点问题.网上的一些方法在我的机器上并没有实现,仅仅能曲折中找到了还有一个方法实现.尽管有点麻烦.但毕竟效果不错. 此方法写在这里,一是和各位分享,二是做个记录,留待以后需求. 不说了,上代码: 以下是dialog自己定义布局文件,是运行任务用的,參考就可以. <? xml version="1.0" encoding=&q

android 自己定义Dialog去除黑色边框

在自己定义Dialog时显示的界面中老是有黑色的边框,以下就介绍使用style去除黑色边框方法. 首先在values/styles定义自己定义样式: <style name="MyDialog" parent="@android:Theme.Dialog"> <item name="android:windowFrame">@null</item> <item name="android:win

android ui定义自己的dialog(项目框架搭建时就写好,之后事半功倍)

自定义一个dialog: 之前有很多博客都有过这方面的介绍,可是个人觉得通常不是很全面,通用性不是很强,一般会定义一个自己的dialog类,然后去使用,难道每一个dialog都要定义一个class吗?? 首先:dialog一般包含一个标题部分,内容部分,按钮部分,风格部分.progressdialog则多一个进度条 那么我们就不妨写一个dialog类,在构造方法中,我们把标题,内容,按钮信息都给他,然后可以show出来 然后,在构造方法中添加一个接口,接口中使用确定,取消等等的按钮的回调. 那么

android中给Dialog设置的动画如何自定义修改参数

============问题描述============ 在android中给Dialog设置动画的方法我只找到Dialog.getWindow().setWindowAnimation(int resID); 这样不是只能在styles里用xml定义动画吗? 但是我现在想要先用程序计算出一个屏幕上的点,在让Dialog从该点开始执行scaleAnimation. 我如何给我Dialog的动画设置起始点之类的参数呢? ============解决方案1============ 自定义一个dial

Android-自定义dialog

自定义Dialog位置和大小 2012-12-06 11:56 2835人阅读 评论(0) 收藏 举报 dialogDialog 目录(?)[+] package angel.devil;import android.app.Activity;import android.app.Dialog;import android.os.Bundle;import android.view.Gravity;import android.view.Window;import android.view.Wi

自己定义控件(二)自己定义Dialog

本节要实现:自己定义一个Dialog 结果例如以下: 步 骤 1.配置register_dialog.xml: 以下是一个自己定义的dialog. 功能是:点击dialog所依附的activity上的"注冊"button,弹出此对话框. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.c

Android创建自定义dialog方法详解-样式去掉阴影效果

在自定义组件时,从已有组件源码中会很大收获.就拿progressDialog来说     间接父类是dialog,想了解dialog继承结构可以去百度,或者    从构造器来说ProgressDialog(Context context, int theme)很明显需要个样式主题文件,我们可以在value文件下自定义一个样式文件.   从外观上需要个动态效果控件和文本框两个属性    ProgressBar mProgress;   TextView mMessageView源码中onCreat

Android-它们的定义Dialog

Android-它们的定义Dialog 2014年4月27日 星期天 天气晴朗 心情平静 本篇博文来分享一个也是开发中常常须要用到的功能-自己定义对话框,这里我用到了Android中的图形资源shape,详细用法,各位看代码吧,Android有多钟图形资源,后面小巫也会总结分享出来.方便各位使用. 我们来看看自己定义Dialog的详细步骤吧: 1.改动系统默认的Dialog样式(风格.主题) 2.自己定义Dialog布局文件 3.能够自己封装一个类.继承自Dialog或者直接使用Dialog类来

(转载)Android常用的Dialog对话框用法

Android常用的Dialog对话框用法 Android的版本有很多通常开发的时候对话框大多数使用自定义或是 Google提供的V4, V7 兼容包来开发保持各个版本的对话框样式统一,所以这里使用的是V7 包里的AlertDialog. 1 import android.app.ProgressDialog; 2 import android.content.DialogInterface; 3 import android.os.Bundle; 4 import android.os.Sys