仿IOS 菜单 ActionSheet Menu For Android_JFrosty的博客-程序员秘密

技术标签: Android开发  android  菜单  menu  ios  菜单控件  

ActionSheet Menu For Android


仿IOS滑动菜单
Date:2015-4-23
SourceCode:https://github.com/FrostySmile/ActionSheetMenu

本文详细介绍类似IOS平台下ActionSheet菜单控件的Android实现全过程,并增加自定义属性。通过本文,你可以学习到以下内容:

  • android自定义view的属性文件的定义和使用(源代码中使用而非xml中)
  • 动态设置局部主题样式(setTheme())
  • 代码创建ViewGroup以及View
  • 如何读取属性文件(attr.xml)的内容
  • 控件监听事件的实现原理(ActionSheetMenu的回调)

效果图

IOS6样式:
样式1
IOS8样式:
样式2
自定义背景:
自定义按钮背景

实现方法步骤

一 、定义相关属性

在attr.xml中定义属性字段。用declare-styleable标签定义属性集合分类baseName,再在内部用attr标签定义具体属性字段名attrName,代码中使用方式则是(R.styleable.baseName_attrName)。代码如下:

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

    <!-- ActionSheetMenu的主题(ios6和ios7) 属性-->
    <declare-styleable name="ActionSheets">
        <attr name="actionSheetStyle" format="reference" />
    </declare-styleable>

    <!-- ActionSheetMenu的具体属性字段 -->
    <declare-styleable name="ActionSheet">

      <attr name="actionSheetBackground" format="color|reference" /><!-- 整个actionSheet背景 -->

      <attr name="actionSheetPadding" format="dimension|reference" /><!-- 整个actionSheet内部间距 -->

      <attr name="actionSheetTextSize" format="dimension|reference" /><!-- actionSheet总体字体大小 -->

      <attr name = "titleButtonBackground" format="color|reference" /><!-- 标题按钮的背景 -->
      <attr name = "titleButtonTextSize" format = "dimension|reference" /><!-- 标题按钮的字体大小 -->
      <attr name = "titleButtonTextColor" format = "color|reference" /><!-- 标题字体的颜色 -->
      <attr name="titleButtonMarginButton" format="dimension|reference" /><!--标题按钮底部距离 -->
      <attr name="titleButtonPadding" format="dimension|reference" /><!--标题按内部间距 -->

      <attr name="otherButtonTopBackground" format="color|reference" /><!-- 主按钮顶部按钮背景-->
      <attr name="otherButtonMiddleBackground" format="color|reference" /><!--  主按钮中间按钮背景-->
      <attr name="otherButtonBottomBackground" format="color|reference" /><!--  主按钮底部按钮背景-->
      <attr name="otherButtonTextColor" format="color|reference" /><!--  主按钮字体颜色-->

      <attr name="otherButtonSingleBackground" format="color|reference" /><!-- 单个主按钮背景-->
      <attr name="otherButtonSpacing" format="dimension|reference" /><!-- 主按钮外部间距 -->

      <attr name="cancelButtonBackground" format="color|reference" /><!-- 取消按钮背景-->
      <attr name="cancelButtonTextColor" format="color|reference" /><!-- 取消按钮字体颜色-->

      <attr name="cancelButtonMarginTop" format="dimension|reference" /><!-- 取消按钮顶部距离 -->

  </declare-styleable>


</resources>

二 、采用自定义的属性

在style.xml中自定义样式style,分别为IOS6和IOS7风格。

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>



    <style name="ActionSheetStyleGray">
        <item name="titleButtonBackground">@android:color/transparent</item>
        <item name="titleButtonTextColor">#ff0000</item>
        <item name="titleButtonTextSize">12sp</item>
        <item name="titleButtonMarginButton">2dp</item>
        <item name="titleButtonPadding">5dp</item>
        <item name="actionSheetBackground">@drawable/as_bg_ios6</item>
        <item name="cancelButtonBackground">@drawable/as_cancel_bt_bg</item>
        <item name="otherButtonTopBackground">@drawable/as_other_bt_bg</item>
        <item name="otherButtonMiddleBackground">@drawable/as_other_bt_bg</item>
        <item name="otherButtonBottomBackground">@drawable/as_other_bt_bg</item>
        <item name="otherButtonSingleBackground">@drawable/as_other_bt_bg</item>
        <item name="cancelButtonTextColor">@android:color/white</item>
        <item name="otherButtonTextColor">@android:color/black</item>
        <item name="actionSheetPadding">10dp</item>
        <item name="otherButtonSpacing">5dp</item>
        <item name="cancelButtonMarginTop">20dp</item>
        <item name="actionSheetTextSize">16sp</item>
    </style>

    <style name="ActionSheetStyleWhite">
        <item name="actionSheetBackground">@android:color/transparent</item>
        <item name="titleButtonBackground">@drawable/actionsheet_top_normal</item>
        <item name="titleButtonTextColor">#ff0000</item>
        <item name="titleButtonTextSize">12sp</item>
        <item name="titleButtonMarginButton">0dp</item>
        <item name="titleButtonPadding">5dp</item>
        <item name="cancelButtonBackground">@drawable/slt_as_ios7_cancel_bt</item>
        <item name="otherButtonTopBackground">@drawable/slt_as_ios7_other_bt_top</item>
        <item name="otherButtonMiddleBackground">@drawable/slt_as_ios7_other_bt_middle</item>
        <item name="otherButtonBottomBackground">@drawable/slt_as_ios7_other_bt_bottom</item>
        <item name="otherButtonSingleBackground">@drawable/slt_as_ios7_other_bt_single</item>
        <item name="cancelButtonTextColor">#1E82FF</item>
        <item name="otherButtonTextColor">#1E82FF</item>
        <item name="actionSheetPadding">10dp</item>
        <item name="otherButtonSpacing">0dp</item>
        <item name="cancelButtonMarginTop">5dp</item>
        <item name="actionSheetTextSize">16sp</item>
    </style>


</resources>

三、自定义ActionSheetMenu

首先继承Dialog,而不是继承Fragment或者Activity等这样无,实现view的OnClickListener接口。在创建布局(包括面板,item)之前,先要读取使用到的属性(readAttribute方法),将属性值封装到内部类中便于使用。为创建的view设置高宽和ID属性等,然后实现onClick方法,根据点击的view调用回调接口的方法,并传出事件源,具体详情功能见代码注释。

public class JFActionSheetMenu extends Dialog implements OnClickListener{
    


    private Context mContext;
    private OnActionSheetItemClickListener mListener;//JFrostyActionSheet回调接口(代理)
    private Attributes mAttrs;//JFrostyActionSheet的属性类,从资源文件读取配置
    private List<String> itemsText;//item标题
    private int itemsTextClolor;
    private boolean mCancelableOnTouchOutside;//点击透明部分是否取消显示dialog

    private View mView;
    private LinearLayout mPanel;
    private View mBg;
    private String titleText = "";
    private int titleTextColor;
    private boolean isShowTitle = false;//是否显示标题
    private String cancelText = "";
    private int cancelTextColor;
    private boolean mDismissed = true;//是否消失了


    private boolean useCustonStyle = false;
    private int titleBg;//标题背景
    private int itemBg;// 主item背景
    private int cancelBg;//取消背景


    //Constructor with context
    public JFActionSheetMenu(Context context,int styleNum) {
        super(context, android.R.style.Theme_Light_NoTitleBar);// 全屏
        this.mContext = context;
        if(styleNum<0){
            context.setTheme(R.style.ActionSheetStyleGray);
        }else if(styleNum>0){
            context.setTheme(R.style.ActionSheetStyleWhite);
        }
        this.mListener = (OnActionSheetItemClickListener) context;
        initViews();
        getWindow().setGravity(Gravity.BOTTOM);
        Drawable drawable = new ColorDrawable();
        drawable.setAlpha(1);// 设置透明背景
        getWindow().setBackgroundDrawable(drawable);

    }

    /**
     * 获取主题属性的方法
     * @return Attributes
     */
    private Attributes readAttribute()
    {
        Attributes attrs = new Attributes(mContext);
        TypedArray a = mContext.getTheme().obtainStyledAttributes(null, R.styleable.ActionSheet,
                R.attr.actionSheetStyle, 0);

        Drawable background = a.getDrawable(R.styleable.ActionSheet_actionSheetBackground);
        if (background != null){
            attrs.background = background;
        }

        Drawable titleBackground = a.getDrawable(R.styleable.ActionSheet_titleButtonBackground);
        if(titleBackground != null){
            attrs.titleButtonBackground = titleBackground;
        }

        Drawable cancelButtonBackground = a.getDrawable(R.styleable.ActionSheet_cancelButtonBackground);
        if (cancelButtonBackground != null)
            attrs.cancelButtonBackground = cancelButtonBackground;

        Drawable otherButtonTopBackground = a.getDrawable(R.styleable.ActionSheet_otherButtonTopBackground);
        if (otherButtonTopBackground != null)
            attrs.otherButtonTopBackground = otherButtonTopBackground;

        Drawable otherButtonMiddleBackground = a
                .getDrawable(R.styleable.ActionSheet_otherButtonMiddleBackground);
        if (otherButtonMiddleBackground != null)
            attrs.otherButtonMiddleBackground = otherButtonMiddleBackground;

        Drawable otherButtonBottomBackground = a
                .getDrawable(R.styleable.ActionSheet_otherButtonBottomBackground);
        if (otherButtonBottomBackground != null)
            attrs.otherButtonBottomBackground = otherButtonBottomBackground;

        Drawable otherButtonSingleBackground = a
                .getDrawable(R.styleable.ActionSheet_otherButtonSingleBackground);
        if (otherButtonSingleBackground != null)
            attrs.otherButtonSingleBackground = otherButtonSingleBackground;

        attrs.cancelButtonTextColor = a.getColor(R.styleable.ActionSheet_cancelButtonTextColor,
                attrs.cancelButtonTextColor);
        attrs.otherButtonTextColor = a.getColor(R.styleable.ActionSheet_otherButtonTextColor,
                attrs.otherButtonTextColor);
        attrs.padding = (int) a.getDimension(R.styleable.ActionSheet_actionSheetPadding, attrs.padding);
        attrs.otherButtonSpacing = (int) a.getDimension(R.styleable.ActionSheet_otherButtonSpacing,
                attrs.otherButtonSpacing);
        attrs.cancelButtonMarginTop = (int) a.getDimension(R.styleable.ActionSheet_cancelButtonMarginTop,
                attrs.cancelButtonMarginTop);
        attrs.actionSheetTextSize = a.getDimensionPixelSize(R.styleable.ActionSheet_actionSheetTextSize,
                (int) attrs.actionSheetTextSize);

        attrs.titleButtonMarginBottom = a.getDimensionPixelSize(R.styleable.ActionSheet_titleButtonMarginButton, attrs.titleButtonMarginBottom);

        a.recycle();
        return attrs;
    }

    //初始化actionSheet
    public void initViews()
    {
        /* 隐藏软键盘 */
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
        {
            View focusView = ((Activity) mContext).getCurrentFocus();
            if (focusView != null)
                imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
        }
        mAttrs = readAttribute();// 获取主题属性
        mView = createView();
        mBg.startAnimation(createAlphaInAnimation());
        mPanel.startAnimation(createTranslationInAnimation());
    }

    //创建移动动画
    private Animation createTranslationInAnimation()
    {
        int type = TranslateAnimation.RELATIVE_TO_SELF;
        TranslateAnimation an = new TranslateAnimation(type, 0, type, 0, type, 1, type, 0);
        an.setDuration(JFConstant.JFCActionSheet.TRANSLATE_DURATION);
        return an;
    }

    //创建时渐变动画
    private Animation createAlphaInAnimation()
    {
        AlphaAnimation an = new AlphaAnimation(0, 1);
        an.setDuration(JFConstant.JFCActionSheet.ALPHA_DURATION);
        return an;
    }

    //移除时移动动画
    private Animation createTranslationOutAnimation()
    {
        int type = TranslateAnimation.RELATIVE_TO_SELF;
        TranslateAnimation an = new TranslateAnimation(type, 0, type, 0, type, 0, type, 1);
        an.setDuration(JFConstant.JFCActionSheet.TRANSLATE_DURATION);
        an.setFillAfter(true);
        return an;
    }

    //透明度渐变动画
    private Animation createAlphaOutAnimation()
    {
        AlphaAnimation an = new AlphaAnimation(1, 0);
        an.setDuration(JFConstant.JFCActionSheet.ALPHA_DURATION);
        an.setFillAfter(true);
        return an;
    }


    /**
     * 点击外部边缘是否可取消
     * 
     * @param cancelable
     * @return
     */
    public JFActionSheetMenu setCancelableOnTouchMenuOutside(boolean cancelable)
    {
        mCancelableOnTouchOutside = cancelable;
        return this;
    }

    /**
     * 为控件添加item成员和标题
     * @param titles
     * @return
     */
    public JFActionSheetMenu addItems(String... titles)
    {
        if (titles == null || titles.length == 0)
            return this;
        itemsText = Arrays.asList(titles);
        createItems();
        return this;
    }

    /**
     * 为控件添加item成员和标题
     * @param titles
     * @return
     */
    public JFActionSheetMenu addItemsWithColor(int color,String... titles)
    {
        if (titles == null || titles.length == 0)
            return this;
        itemsTextClolor = color;
        itemsText = Arrays.asList(titles);
        createItems();
        return this;
    }





    public JFActionSheetMenu setItemsTextClolor(int itemsTextClolor) {
        this.itemsTextClolor = itemsTextClolor;
        return this;
    }

    public JFActionSheetMenu setTitleTextColor(int titleTextColor) {
        this.titleTextColor = titleTextColor;
        return this;
    }

    public JFActionSheetMenu setCancelTextColor(int cancelTextColor) {
        this.cancelTextColor = cancelTextColor;
        return this;
    }

    /**
     * 创建基本的背景视图
     */
    private View createView()
    {
        FrameLayout parent = new FrameLayout(mContext);
        FrameLayout.LayoutParams parentParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        parentParams.gravity = Gravity.BOTTOM;
        parent.setLayoutParams(parentParams);
        mBg = new View(mContext);
        mBg.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mBg.setBackgroundColor(Color.argb(136, 0, 0, 0));
        mBg.setId(JFConstant.JFCActionSheet.BG_VIEW_ID);
        mBg.setOnClickListener(this);

        mPanel = new LinearLayout(mContext);
        FrameLayout.LayoutParams mPanelParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        mPanelParams.gravity = Gravity.BOTTOM;
        mPanel.setLayoutParams(mPanelParams);
        mPanel.setOrientation(LinearLayout.VERTICAL);
        parent.addView(mBg);
        parent.addView(mPanel);
        return parent;
    }

    /**
     * ***************************创建MenuItem* ***************************
     */
    @SuppressWarnings("deprecation")
    private void createItems()
    {

        if(isShowTitle){
            //设置标题按钮
            TextView titleBtn = new TextView(mContext);
            titleBtn.getPaint().setFakeBoldText(true);//加粗
            titleBtn.setText(titleText);
            titleBtn.setOnClickListener(this);
            titleBtn.setId(JFConstant.JFCActionSheet.TITLE_BUTTON_ID);
            titleBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX,mAttrs.titleButtonTextSize);
            titleBtn.setTextColor(titleTextColor==0?mAttrs.titleButtonTextColor:titleTextColor);
            if(useCustonStyle && titleBg>0){
                titleBtn.setBackgroundResource(titleBg);
            }else{
                titleBtn.setBackgroundDrawable(mAttrs.titleButtonBackground);
            }
            titleBtn.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams paramsTitle = createButtonLayoutParams();
            titleBtn.setPadding(0,mAttrs.titleButtonPadding, 0, mAttrs.titleButtonPadding);
            paramsTitle.bottomMargin = mAttrs.titleButtonMarginBottom;
            mPanel.addView(titleBtn, paramsTitle);
        }


        if (itemsText != null && itemsText.size() > 0)
            for (int i = 0; i < itemsText.size(); i++)
            {
                Button bt = new Button(mContext);
                bt.setId(JFConstant.JFCActionSheet.CANCEL_BUTTON_ID + i + 1);
                bt.setOnClickListener(this);
                if(useCustonStyle&& itemBg>0){
                    bt.setBackgroundResource(itemBg);
                }else{
                    bt.setBackgroundDrawable(getOtherButtonBg(itemsText.toArray(new String[itemsText.size()]), i));
                }
                bt.setText(itemsText.get(i));
                bt.setTextColor(itemsTextClolor==0?mAttrs.otherButtonTextColor:itemsTextClolor);
                bt.setTextSize(TypedValue.COMPLEX_UNIT_PX, mAttrs.actionSheetTextSize);
                if (i > 0)
                {
                    LinearLayout.LayoutParams params = createButtonLayoutParams();
                    params.topMargin = mAttrs.otherButtonSpacing;
                    mPanel.addView(bt, params);
                } else
                    mPanel.addView(bt);
            }


        //取消按钮的设置
        Button bt = new Button(mContext);
        bt.getPaint().setFakeBoldText(true);
        bt.setTextSize(TypedValue.COMPLEX_UNIT_PX, mAttrs.actionSheetTextSize);
        bt.setId(JFConstant.JFCActionSheet.CANCEL_BUTTON_ID);//-1
        if(useCustonStyle && cancelBg>0){
            bt.setBackgroundResource(cancelBg);
        }else{
            bt.setBackgroundDrawable(mAttrs.cancelButtonBackground);
        }
        bt.setText(cancelText);
        bt.setTextColor(cancelTextColor==0?mAttrs.cancelButtonTextColor:cancelTextColor);
        bt.setOnClickListener(this);
        LinearLayout.LayoutParams params = createButtonLayoutParams();
        params.topMargin = mAttrs.cancelButtonMarginTop;
        mPanel.addView(bt, params);

        mPanel.setBackgroundDrawable(mAttrs.background);
        mPanel.setPadding(mAttrs.padding, mAttrs.padding, mAttrs.padding, mAttrs.padding);
    }


    public LinearLayout.LayoutParams createButtonLayoutParams()
    {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        return params;
    }


    /**
     * item按钮的颜色
     * 
     * @param titles
     * @param i
     * @return
     */
    private Drawable getOtherButtonBg(String[] titles, int i)
    {
        if (titles.length == 1)
            if(isShowTitle){
                return mAttrs.otherButtonBottomBackground;
            }else{
                return mAttrs.otherButtonSingleBackground;
            }
        else if (titles.length == 2)
            switch (i)
            {
            case 0:
                if(isShowTitle){
                    return mAttrs.otherButtonMiddleBackground;
                }else{
                    return mAttrs.otherButtonTopBackground;
                }
            case 1:
                return mAttrs.otherButtonBottomBackground;
            }
        else if (titles.length > 2)
        {
            if (i == 0){
                if(isShowTitle){
                    return mAttrs.otherButtonMiddleBackground;
                }
                return mAttrs.otherButtonTopBackground;
            }
            else if (i == (titles.length - 1))
                return mAttrs.otherButtonBottomBackground;
            return mAttrs.getOtherButtonMiddleBackground();
        }
        return null;
    }

    /**
     * 显示菜单
     */
    public void showMenu()
    {
        if (!mDismissed)
            return;
        show();
        getWindow().setContentView(mView);
        mDismissed = false;
    }

    /**
     * dissmiss Menu菜单
     */
    public void dismissMenu()
    {
        if (mDismissed)
            return;
        onDismiss();
        mDismissed = true;
    }

    /**
     * dismiss时的处理
     */
    private void onDismiss()
    {
        mPanel.startAnimation(createTranslationOutAnimation());
        mBg.startAnimation(createAlphaOutAnimation());
        mView.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismiss();
            }
        }, JFConstant.JFCActionSheet.ALPHA_DURATION);
    }


    /**
     * 标题按钮的标题文字
     * 
     * @param title
     * @return
     */
    public JFActionSheetMenu setTitleButtonTextAndColor(String title,int color)
    {
        if(TextUtils.isEmpty(title)){
            isShowTitle = false;
        }else{
            this.titleText = title;
            this.titleTextColor = color;
            isShowTitle = true;
        }
        return this;
    }

    /**
     * 标题按钮的标题文字
     * 
     * @param strId
     * @return
     */
    public JFActionSheetMenu setTitleButtonTextAndColor(int strId,int color)
    {
        return setTitleButtonTextAndColor(mContext.getString(strId),color);
    }



    /**
     * 取消按钮的标题文字
     * 
     * @param title
     * @return
     */
    public JFActionSheetMenu setCancelButtonTextAndColor(String title,int color)
    {
        this.cancelText = title;
        this.cancelTextColor = color;
        return this;
    }

    /**
     * 取消按钮的标题文字
     * 
     * @param strId
     * @return
     */
    public JFActionSheetMenu setCancelButtonTextAndColor(int strId,int color)
    {
        return setCancelButtonTextAndColor(mContext.getString(strId),color);
    }



    /**
     * 设置实现了本控件代理的对象
     * @param listener
     * @return JFrostyActionSheet具体实例
     */
    public JFActionSheetMenu setItemClickListener(OnActionSheetItemClickListener listener)
    {
        this.mListener = listener;
        return this;
    }

    /**
     * 设置是否使用自定义按钮背景,当为true时才有效
     * @param listener
     * @return JFrostyActionSheet具体实例
     */
    public JFActionSheetMenu setUseCustonStyle(boolean use)
    {
        this.useCustonStyle = use;
        return this;
    }


    public JFActionSheetMenu setTitleBg(int titleBg) {
        this.titleBg = titleBg;
        return this;
    }

    public JFActionSheetMenu setItemBg(int itemBg) {
        this.itemBg = itemBg;
        return this;
    }

    public JFActionSheetMenu setCancelBg(int cancelBg) {
        this.cancelBg = cancelBg;
        return this;
    }

    /**
     * 点击背景是否消失
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if( v.getId() == JFConstant.JFCActionSheet.TITLE_BUTTON_ID || (v.getId() == JFConstant.JFCActionSheet.BG_VIEW_ID && !mCancelableOnTouchOutside))
            return;
        dismissMenu();
        if (v.getId() != JFConstant.JFCActionSheet.CANCEL_BUTTON_ID && v.getId() != JFConstant.JFCActionSheet.BG_VIEW_ID)
        {
            if (mListener != null)
                mListener.onItemClick(v,v.getId() - JFConstant.JFCActionSheet.CANCEL_BUTTON_ID - 1);
        }else if(v.getId() == JFConstant.JFCActionSheet.CANCEL_BUTTON_ID){
            mListener.onCanceClick(v);
        }

    }



    /**
     * @description 自定义属性的控件主题属性
     * @author JFrosty
     */
    private class Attributes
    {
    
        private Context mContext;

        private Drawable background;
        private Drawable titleButtonBackground;//
        private Drawable cancelButtonBackground;
        private Drawable otherButtonTopBackground;
        private Drawable otherButtonMiddleBackground;
        private Drawable otherButtonBottomBackground;
        private Drawable otherButtonSingleBackground;
        private int titleButtonTextColor;//
        private int cancelButtonTextColor;
        private int otherButtonTextColor;
        private int padding;
        private int otherButtonSpacing;
        private int cancelButtonMarginTop;
        private float actionSheetTextSize;
        private float titleButtonTextSize;//
        private int titleButtonPadding;
        private int titleButtonMarginBottom;

        public Attributes(Context context)
        {
            mContext = context;
            this.background = new ColorDrawable(Color.TRANSPARENT);
            this.cancelButtonBackground = new ColorDrawable(Color.BLACK);
            ColorDrawable gray = new ColorDrawable(Color.GRAY);
            this.titleButtonBackground = gray;
            this.otherButtonTopBackground = gray;
            this.otherButtonMiddleBackground = gray;
            this.otherButtonBottomBackground = gray;
            this.otherButtonSingleBackground = gray;
            this.cancelButtonTextColor = Color.WHITE;
            this.otherButtonTextColor = Color.BLACK;
            this.titleButtonTextColor=Color.RED;
            this.padding = dp2px(10);
            this.otherButtonSpacing = dp2px(2);
            this.cancelButtonMarginTop = dp2px(10);
            this.actionSheetTextSize = dp2px(16);
            this.titleButtonTextSize = dp2px(14);
            this.titleButtonPadding = dp2px(20);
            this.titleButtonMarginBottom = dp2px(0);

        }

        //dp转px
        private int dp2px(int dp)
        {
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, mContext.getResources()
                    .getDisplayMetrics());
        }

        //获取中间部分item背景(无圆角)
        public Drawable getOtherButtonMiddleBackground()
        {
            if (otherButtonMiddleBackground instanceof StateListDrawable)
            {
                TypedArray a = mContext.getTheme().obtainStyledAttributes(null, R.styleable.ActionSheet,
                        R.attr.actionSheetStyle, 0);
                otherButtonMiddleBackground = a
                        .getDrawable(R.styleable.ActionSheet_otherButtonMiddleBackground);

                a.recycle();
            }
            return otherButtonMiddleBackground;
        }

    }

    /**
     * JFrostyActionSheet回调接口
     */
    public static interface OnActionSheetItemClickListener
    {
    
        void onItemClick(View view,int itemPosition);
        void onCanceClick(View view);
    }


}

四、使用ActionSheetMenu

构造传入两个参数初始化menu,第一个参数是上下文,第二个参数代表菜单样式,传入的值是整数,如果小于0则是IOS6风格,如果大于0则是IOS7风格。否则需要自定义按钮背景图片,自定义背景图需要设置menu.setUseCustonStyle(true)即使用自定义风格true。初始化代码如下:

menu = new JFActionSheetMenu(this,style);//style<0:ios6,style>0:ios7

部分主要属性设置及说明如下:

        /*如果是使用自定义(设置了          menu.setUseCustonStyle(isCuston)),且设置对应的背景才有效
         * 且必须放在创建各按钮之前
         *注意:凡是在代码中对属性进行设置,都要在创建item之前实现,即,放在setCancelButtonTextAndColor()、addItems()方法之前
         * */
        menu.setTitleBg(R.drawable.as_other_bt_bg);
        menu.setItemBg(R.drawable.btn_style_one_normal);
        menu.setCancelBg(R.drawable.as_cancel_bt_bg);
        if(isCuston){
            menu.setItemsTextClolor(Color.WHITE);
        }
        //设置取消按钮
        menu.setCancelButtonTextAndColor("cancel",Color.RED);// 在主item前面添加
        //设置标题(不设置则不显示标题)
        if( style >= 0){
            menu.setTitleButtonTextAndColor("请选择照片", Color.BLUE);
        }

        //设置主item
        menu.addItems("拍照","选择照片","网络获取");


        //主item监听
        menu.setItemClickListener(this);
        //取消按钮监听
        menu.setCancelableOnTouchMenuOutside(true);
        //显示menu
        menu.showMenu();

注意:纯拷贝代码会报错,因为代码中使用的额外的资源文件没有,源代码和资源文件下载链接顶部已给出!

Source On GitHub::https://github.com/FrostySmile/ActionSheetMenu

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u011445031/article/details/45222939

智能推荐

用php写杨辉三角,PHP实现杨辉三角示例_莫二牛的博客-程序员秘密

error_reporting(0);// $iLine=5;//输出杨辉三角的函数function YangHui($iLine){for ($i = 0;$i &lt;= $iLine;$i++)//行{for ($j = 0;$j &lt;= $i;$j++)//列{if ($i == $j)//行=列(也就是最后一列)或者第一行和第一列{$a[$i][$j] = 1;echo $a[$i...

Java程序/课程设计_x_uhen的博客-程序员秘密_java课程设计ppt

public static void main{printf("Java课程设计资源介绍【代码+报告】");KeSheName=["1.java飞机订票系统源代码2.人事管理系统【有ppt】3.人机五子棋4.即时通信软件5.基于WEB的软件工程课程试题库管理系统6.宿舍管理系统7.电脑端笔记本开发设计8.远程屏幕监控系统9.食品公司管理系统jsp10.聊天室"]pri...

linux系统中安装jdk出现bash: ./java: cannot execute binary file 问题_逆风也是一种成长的博客-程序员秘密

问题现象描述: 我自己装了一个虚拟机并安装了linux系统,在这个系统上安装jdk的时候出现了一下错误: 执行这个命令 ./java bash: ./java: cannot execute binary file在网上找原因,发现是我装的linux系统是32位的,而我装的jdk是64位的,所出现上述问题,所以以后安装时要查一下自己的系统是32位还是64位

轻量级自适应个人自动发卡源码全开源 附详细图文安装教程_词不达yi、的博客-程序员秘密_自动发卡源码

介绍:轻量级自适应个人自助发卡去除多余的文件及代码后台添加新功能及快速邮件配置更新删除原来的发件程序可以修改前台文件信息重新规划文件布局等等将源码上传至虚拟机或者服务器并解压 访问域名/install.php安装(填写数据库相关信息) 进入后台修改网站相关信息。(温馨提醒:记得修改登陆路径和账号,以及支付接口)下载地址:https://wwc.lanzouo.com/iLUIRy1h2ti...

iPhone 大降价;谷歌再爆丑闻;京东云金山云回应合并传闻 | 极客头条_CSDN资讯的博客-程序员秘密

「CSDN 极客头条」,是从 CSDN 网站延伸至官方微信公众号的特别栏目,专注于一天业界事报道。风里雨里,我们将每天为朋友们,播报最新鲜有料的新闻资讯,让所有技术人,时...

oracle11数据库冷备迁移,Oracle 11g 数据库迁移_铁血宰相张伯伦的博客-程序员秘密

由于服务器更换,或者硬盘损坏等问题,在有些场景下,我们需要对数据库进行迁移。Oracle 数据库有多种备份方式,如果可以停机,建议最好使用冷备的方式,直接迁移数据文件,这样效率会比较高。由于两台主机都是Windows server,为了方便直接使用复制文件的方式,由于特殊原因,迁移前的数据目录和迁移后的数据目录是不一致的。直接迁移数据后,启动会报如下错误:SQL&gt;startupORACLE...

随便推点

python聚合函数_72.Python中ORM聚合函数详解:Avg,aggregate,annotate_weixin_39520149的博客-程序员秘密

聚合函数:如果你用原生SQL语句,则可以使用聚合函数提取数据。比如提取某个商品销售的数量,那么就可以使用Count,如果想要知道销售的平均价格,那么就可以使用Avg。聚合函数是通过aggregate方法来实现的,在讲解这些聚合函数的用法的时候,都是基于以下的模型来实现的。示例代码如下:'''python#模型要放在app当中。所以首先要在终端命令行窗口,执行命令:python manage.py ...

智慧云教育平台实战项目笔记_哈希疯的博客-程序员秘密

智慧云智慧教育平台实战项目笔记一、简介课程内容:智慧云教育平台管理后台、智慧云教育平台学生端、项目的正式部署1、技术说明后端技术:JDK1.8 + SpringBoot + MyBatis + Shiro缓存框架:Redis数据库:MySQL 5.7前端技术:Element-UI + Vue开发工具:IDEA 2019.3.3项目管理工具:Maven、Git使用最主流的框架 SpringBoot + Vue 实现完全前后端分离2、核心功能介绍管理后台核心功能:RBAC权限管理、

java怎么调用7zip进行压缩_JAVA使用7-zip解压缩带密码的Zip文件(非Proccess方法)..._Xi Yang的博客-程序员秘密

首先到sourceforge网站下载sevenzipjbinding压缩包我下载的版本是sevenzipjbinding-4.65-1.04-rc-extr-only-AllWindows.zippublicvoidunzipDirWithPassword( final String sourceZipFile ,final String destinationDir , final String...

新浪微博 ios/android 你所访问的站点在新浪微博的认证失败 解决方法_蛀牙kk的博客-程序员秘密

Problem:一般遇到新浪授权时,没有回调授权页面而是显示如下界面,都是授权回调页搞的鬼。访问出错了!你所访问的站点在新浪微博的认证失败,请你联系阿k点灯或者稍后再试。(error:redirect_uri_mismatch)Solution:1.ios开发 客户端可不填写授权回调页——官方给出的三个sdk,其中第二个sdk默认授权回调页为空,第一个s

Application对象常用属性/Window对象的常用属性_fxhome的博客-程序员秘密_application window

Application对象常用属性  1、MainWindow  获取当前Application中的主窗体,如果不进行修改,默认获取到的是第一个调用Show()的窗体对象  2、Windows  获取当前Application管理的所有窗体实例 集合类型  3、ShutdownModel  这是一个枚举类型,用以决定何时应该结束这个Application的声明周期,枚举值有三个  OnExplic...

(六)通过pygame让游戏背景图像实现交替滚动_fjswcjswzy的博客-程序员秘密

文章目录原理解决办法具体代码原理在游戏中,需要如何将游戏的背景实现交替滚动?利用运动是相对的游戏启动后,背景图像会连续不断地向下方移动,在视觉上就会产生英雄的飞机不断向上方飞行的错觉,这在很多跑酷类游戏中是常见的如果只是单单一张背景图向下移动,如下图所示,可以看到,如果只是一张背景图向下移动的话,那么游戏主界面上方就会出现没有背景图的情况(红色区域)那么要怎么解决这个问题呢??用两张一样的背景图,另一张叠放在屏幕的正上方(如下图)让两张背景图像同时向下移动,那么上文所说的“红色

推荐文章

热门文章

相关标签