仿IOS 菜单 ActionSheet Menu For Android-程序员宅基地

技术标签: 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

智能推荐

属性动画分析与使用_问题属性分析动画-程序员宅基地

文章浏览阅读1.1k次。引言:在讲述属性动画之前,先引入一个问题:如何以动画的形式,让Button的宽度在1000ms内利由40dp增长到100dp,如图1.1所示:图1.1 目标缩放动效首先,我们会想到利用View Animation中的ScaleAnimation来实现,但是,ScaleAnimation所做的是一个整体的缩放,虽然能改变Button的宽度,同时也会将字体进行拉伸,其动画效果就会如下图_问题属性分析动画

PHP数组函数 array_intersect_ukey (计算数组的交集,使用回调函数比较key)-程序员宅基地

文章浏览阅读171次。在PHP中,数组函数 array_intersect_ukey () 用来计算多个数组的交集,和array_intersect_key不同的是,此函数使用回调函数比较键名来计算数组的交集。函数语法:array_intersect_ukey(array$array1,array$array2[,array$...],callable$key_compare_func):array函数参数说明:参数 描述 array1 必需..._array_intersect_ukey

android mk 自定义变量,查看Android.mk文件中的变量的值-程序员宅基地

文章浏览阅读393次。当某个Android.mk中包含如下:LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_C_INCLUDES+=$(LOCAL_PATH) $(JNI_H_INCLUDE) \我们想查看$(LOCAL_PATH)或者$(JNI_H_INCLUDE)的值是什么.我们可以在上面的内容最后,加一句#这一句的意思是打印变量$(JNI_H_INC..._$(jni_h_include)

上海交通大学软件专硕,复试平均分413分!-程序员宅基地

文章浏览阅读1k次。上海交通大学是一所985大学,也是著名的交通大学的其中之一。上海交通大学计算机学科评估A,软件工程学科评估A-,在985大学中排名上游,是计算机实力很强的大学。图片来源:上海交通大学官网h..._上海交通大学计算机专硕

Win10 dos命令查看端口占用及关闭进程-程序员宅基地

文章浏览阅读4.3k次。你需要安装很多东西,请按照以下顺序安装:安装的版本包也不能错:curl -Ohttp://mirrors.kernel.org/gnu/m4/m4-1.4.13.tar.gztar -xzvf m4-1.4.13.tar.gzcd m4-1.4.13./configure --prefix=/usr/localmakesudo make installcd

模态对话框和非模态对话框区别-程序员宅基地

文章浏览阅读72次。按工作方式不同,可将对话框分成两类: ??模式对话框(modal dialog box模态对话框):在关闭模式对话框之前,程序不能进行其他工作(如一般的“打开文件”对话框) ??无模式对话框(modeless dialog box 非模态对话框):模式对话框打开后,程序仍然能够进行其他工作(如一般的“查找与替换”对话框) 两者的区别: 一. 非模态对话框的模板必须具有Visible风格(Visib...

随便推点

pp-程序员宅基地

文章浏览阅读38次。build/config.js 改 8080端口 build/webpack.dev.conf.js 改路径简写 alias:{ 'vux-components':'vux/dist/components'; }转载于:https://www.cnblogs.com/gyz418/p/6160986.html

C语言:向一个已排序好的数组中插入一个数重新进行排序_往有序数组里插入一个数重新排序-程序员宅基地

文章浏览阅读6.5k次,点赞11次,收藏51次。C语言学习记录之向一个已排序好的数组中插入一个数重新进行排序int main() { int arr[11] = { 1,3,5,7,9,11,13,15,17,19 };// 例如数组现存在10个数 int num; scanf("%d", &num); printf("初始序列:"); for (int i = 0;i < 10;i++) { printf("%5d", arr[i]); } printf("\n_往有序数组里插入一个数重新排序

网络安全 | C语言实现MD5信息摘要算法-程序员宅基地

文章浏览阅读637次,点赞2次,收藏4次。算法不难,只是要注意大端小端,以及使用合适的数据结构。很久没用过C语言了,网上有一篇花式位运算的,我实在学不来,不过合理使用unsigned int (32位)和 unsigned char(8位)还是能方便很多的,还有就是#define 常量的用处(比如#define F(b, c, d) ((b &amp;amp;amp; c) | (~b &amp;amp;amp; d))),之前没这么运用过,发现还挺好用的。MD5概...

吴恩达 DeepLearning 第二课第二周题目(包括选择题)_吴恩达 深度学习 第二周编程题目-程序员宅基地

文章浏览阅读1.3k次。选择题: 编程题下载链接所有题目不提供答案,有不确定的,可以讨论。_吴恩达 深度学习 第二周编程题目

ORACLE 11g Result cache使用指南-程序员宅基地

文章浏览阅读93次。何为result cache?result cache,结果缓存,当表的访问方式以读为主前提下,从一张大表中过滤出少量的记录作为结果集的查询语句适合把查询结果集放入result cache,后续相同的查询语句可以直接从res...

IDEA:FATAL ERROR in native method: processing of -javaagent failed报错-程序员宅基地

文章浏览阅读3.9k次。FATAL ERROR in native method: processing of -javaagent failed报错,找了好多方案都未能解决,于是我用了最简单粗暴的办法。_-javaagent failed