自定义多选 dialog

dialog源码:

package com.marktony.zhihudaily.util;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.marktony.zhihudaily.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2017/3/12.
 */

public class ActionSheetDialog {
    private static final String TAG = "ASDialog";
    private Context context;
    private Dialog dialog;
    private TextView txt_title;
    private TextView txt_cancel;
    private LinearLayout lLayout_content;
    private ScrollView sLayout_content;
    private boolean showTitle = false;
    private List<SheetItem> sheetItemList;
    private Display display;
    private Window dialogWindow;
    private WindowManager.LayoutParams lp;
    private View mView;
    private int drawableId = -1;
    public ActionSheetDialog(Context context) {
        this.context = context;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        display = windowManager.getDefaultDisplay();
    }

    /**
     *
     * @return
     */
    public ActionSheetDialog builder() {
        // 获取Dialog布局
        mView = LayoutInflater.from(context).inflate(R.layout.toast_view_actionsheet, null);

        // 设置Dialog最小宽度为屏幕宽度
        mView.setMinimumWidth(display.getWidth());

        // 获取自定义Dialog布局中的控件
        sLayout_content = (ScrollView) mView.findViewById(R.id.sLayout_content);
        lLayout_content = (LinearLayout) mView.findViewById(R.id.lLayout_content);
        txt_title = (TextView) mView.findViewById(R.id.txt_title);
        txt_cancel = (TextView) mView.findViewById(R.id.txt_cancel);
        txt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        // 定义Dialog布局和参数
        dialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        dialog.setContentView(mView);
        dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        lp = dialogWindow.getAttributes();

        //x,y代表dialog相对于Window的位置,跟一般View的X和y一样的
        lp.x = 0;
        lp.y = 0;
        dialogWindow.setAttributes(lp);

        return this;
    }

    /**
     * 关闭取消选项
     * @return
     */
    public ActionSheetDialog closeCancel(){
        txt_cancel.setVisibility(View.GONE);
        return this;
    }

    /**
     * 设置dialog标题
     * @param title
     * @return
     */
    public ActionSheetDialog setTitle(String title) {
        showTitle = true;
        if(txt_title==null){
            new NullPointerException("请先实例化ActionSheetDialog(未调用ActionSheetDialog builder())");
        }
        txt_title.setVisibility(View.VISIBLE);
        txt_title.setText(title);
        return this;
    }

    /**
     * 设置Dialog对于界面的位置
     * 默认靠左考下
     * @param gravity
     * @return
     */
    public ActionSheetDialog setGravity(int gravity){
        if(dialogWindow==null){
            new NullPointerException("请先实例化ActionSheetDialog(未调用ActionSheetDialog builder())");
        }
        dialogWindow.setGravity(gravity);

        return this;
    }

    /**
     * 设置背景
     * @param drawableId Drawable资源ID
     * @return
     */
    public ActionSheetDialog setBackground(int drawableId){
//        dialogWindow.setBackgroundDrawableResource(drawableId);
        this.drawableId = drawableId;
        return this;
    }
    /**
     *
     * @param width dialog宽度,默认为最大值——-1     -2 代表宽度自适应
     * @param x 默认值为2500
     * @param y 默认值为2500
     * @param alpha 默认值为1
     * @return
     */
    public ActionSheetDialog setPosition(int width,int x,int y,int alpha){
        if(dialogWindow==null){
            new NullPointerException("请先实例化ActionSheetDialog(未调用ActionSheetDialog builder())");
        }
        boolean isUpdate = false;
         if(width!=-1){
            isUpdate = true;
             lp.width = width;
         }
        if(x!=2500){
            isUpdate = true;
            lp.x = LinearLayout.LayoutParams.WRAP_CONTENT;
        }
        if(y!=2500){
            isUpdate = true;
            lp.y = y;
        }
        if(alpha!=1){
            lp.alpha = alpha;
        }
        if(isUpdate){
            dialogWindow.setAttributes(lp);
        }
        return this;
    }
   public ActionSheetDialog setCancelable(boolean cancel) {
        dialog.setCancelable(cancel);
        return this;
    }

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

    /**
     * @param strItem  条目名称
     * @param color    条目字体颜色,设置null则默认蓝色
     * @param listener
     * @return
     */
    public ActionSheetDialog addSheetItem(String strItem, SheetItemColor color,
                                          OnSheetItemClickListener listener) {
        if (sheetItemList == null) {
            sheetItemList = new ArrayList<>();
        }
        sheetItemList.add(new SheetItem(strItem, color, listener));
        return this;
    }

    /**
     *
     * @param strItem   条目字体
     * @param drawableId    icon图标
     * @param color     条目字体颜色,设置null则默认蓝色
     * @param listener  点击事件
     * @return
     */
    public ActionSheetDialog addSheetItem(String strItem,int drawableId, SheetItemColor color,
                                          OnSheetItemClickListener listener) {
        if (sheetItemList == null) {
            sheetItemList = new ArrayList<>();
        }
        sheetItemList.add(new SheetItem(strItem,drawableId, listener,color));
        return this;
    }

    /**
     * 设置条目布局
     */
    @SuppressWarnings("deprecation")
    private void setSheetItems() {
        if (sheetItemList == null || sheetItemList.size() <= 0) {
            return;
        }

        int size = sheetItemList.size();

        // TODO 高度控制,非最佳解决办法
        // 添加条目过多的时候控制高度
        if (size >= 7) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) sLayout_content.getLayoutParams();
            params.height = display.getHeight() / 2;
            sLayout_content.setLayoutParams(params);
        }

        // 循环添加条目
        for (int i = 1; i <= size; i++) {
            final int index = i;
            SheetItem sheetItem = sheetItemList.get(i - 1);
            String strItem = sheetItem.name;
            SheetItemColor color = sheetItem.color;
            final OnSheetItemClickListener listener = sheetItem.itemClickListener;
            int iconId = sheetItem.iconId;
            TextView textView = new TextView(context);
            textView.setText(strItem);
            textView.setTextSize(18);
            textView.setGravity(Gravity.CENTER);
            if(iconId!=-1){
//                textView.setD
                Drawable mDrawable = context.getResources().getDrawable(iconId);
                mDrawable.setBounds(0, 0, mDrawable.getMinimumWidth(),mDrawable.getMinimumHeight());  //此为必须写的
                textView.setCompoundDrawables(mDrawable, null, null, null);
                textView.setCompoundDrawablePadding(4);

            }
            if(drawableId!=-1){
//               textView.setBackgroundColor(context.getResources().getColor(R.color.show_image_bg_black));
                Log.d(TAG, "setSheetItems: "+ -1);
            }else{
                Log.d(TAG, "setSheetItems: "+ -2);
                // 背景图片
                if (size == 1) {
                    if (showTitle) {
                        textView.setBackgroundResource(R.drawable.actionsheet_bottom_selector);
                    } else {
                        textView.setBackgroundResource(R.drawable.actionsheet_single_selector);
                    }
                } else {
                    if (showTitle) {
                        if (i >= 1 && i < size) {
                            textView.setBackgroundResource(R.drawable.actionsheet_middle_selector);
                        } else {
                            textView.setBackgroundResource(R.drawable.actionsheet_bottom_selector);
                        }
                    } else {
                        if (i == 1) {
                            textView.setBackgroundResource(R.drawable.actionsheet_top_selector);
                        } else if (i < size) {
                            textView.setBackgroundResource(R.drawable.actionsheet_middle_selector);
                        } else {
                            textView.setBackgroundResource(R.drawable.actionsheet_bottom_selector);
                        }
                    }
                }
            }


            // 字体颜色
            if (color == null) {
                textView.setTextColor(Color.parseColor(SheetItemColor.Blue
                        .getName()));
            } else {
                textView.setTextColor(Color.parseColor(color.getName()));
            }

            // 高度
            float scale = context.getResources().getDisplayMetrics().density;
            int height = (int) (45 * scale + 0.5f);
            textView.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, height));

            // 点击事件
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(index);
                    dialog.dismiss();
                }
            });

            lLayout_content.addView(textView);
        }
    }

    public void show() {
        setSheetItems();
        dialog.show();
    }

    public interface OnSheetItemClickListener {
        void onClick(int which);
    }

    public class SheetItem {
        String name;
        OnSheetItemClickListener itemClickListener;
        SheetItemColor color;
        int iconId = -1;

        public SheetItem(String name, SheetItemColor color, OnSheetItemClickListener itemClickListener) {
            this.name = name;
            this.color = color;
            this.itemClickListener = itemClickListener;
        }

        public SheetItem(String name,int iconId, OnSheetItemClickListener itemClickListener, SheetItemColor color) {
            this.name = name;
            this.itemClickListener = itemClickListener;
            this.color = color;
            this.iconId = iconId;
        }
    }

    public enum SheetItemColor {
        Blue("#037BFF"), Red("#FD4A2E"), Grey("#6C6C6C"),White("#FFFFFF");

        private String name;

        private SheetItemColor(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}

相关xml文件:

style:

  <!-- 自定义多选按钮的样式-->
    <style name="ActionSheetDialogStyle" parent="@android:style/Theme.Dialog">

        <!-- 背景透明 -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <!-- 浮于Activity之上 -->
        <item name="android:windowIsFloating">true</item>
        <!-- 边框 -->
        <item name="android:windowFrame">@null</item>
        <!-- Dialog以外的区域模糊效果 -->
        <item name="android:backgroundDimEnabled">true</item>
        <!-- 无标题 -->
        <item name="android:windowNoTitle">true</item>
        <!-- 半透明 -->
        <item name="android:windowIsTranslucent">true</item>
        <!-- Dialog进入及退出动画 -->
        <item name="android:windowAnimationStyle">@style/ActionSheetDialogAnimation</item>
    </style>
<!-- View动画 -->
    <style name="ActionSheetDialogAnimation" parent="@android:style/Animation.Dialog">
        <item name="android:windowEnterAnimation">@anim/actionsheet_dialog_in</item>
        <item name="android:windowExitAnimation">@anim/actionsheet_dialog_out</item>
    </style>

View动画:

actionsheet_dialog_in:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="200"
    android:fromYDelta="100%"
    android:toYDelta="0" />

actionsheet_dialog_out:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="200"
    android:fromYDelta="0"
    android:toYDelta="100%" />

内容layout:

<?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="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/txt_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/toast_actionsheet_top_normal"
        android:gravity="center"
        android:minHeight="45dp"
        android:paddingBottom="10dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="10dp"
        android:textColor="@color/actionsheet_gray"
        android:textSize="13sp"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/sLayout_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadingEdge="none">

        <LinearLayout
            android:id="@+id/lLayout_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"/>
    </ScrollView>

    <TextView
        android:id="@+id/txt_cancel"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/actionsheet_single_selector"
        android:gravity="center"
        android:text="取消"
        android:textColor="@color/actionsheet_blue"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

以上内容总结自大神demo,暂时无效果图。欢迎吐槽!
更新内容:增加宽度设置、位置设置、位置设置、背景色设置等!
最新使用:

        new ActionSheetDialog(context)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .closeCancel()
                .addSheetItem(
                        "查看图片",
                        ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                               //查看图片
                            }
                        })
                .addSheetItem("保存图片", ActionSheetDialog.SheetItemColor.Grey,
                        new ActionSheetDialog.OnSheetItemClickListener(){

                            @Override
                            public void onClick(int which) {
                               //保存图片
                                });
                            }
                        })
                .addSheetItem("分享图片", ActionSheetDialog.SheetItemColor.Grey,
                        new ActionSheetDialog.OnSheetItemClickListener(){

                            @Override
                            public void onClick(int which) {
                               //分享图片
                                });
                            }
                        })
                .show();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值