美文网首页
Android下拉菜单组件

Android下拉菜单组件

作者: SeekLife0 | 来源:发表于2023-01-21 15:41 被阅读0次

前言:
复制文件到工程,根据需要修改代码即可。

b0b2ecabe2b419e53d51f096d268167.png

组件代码
java

package com.example.xy.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.xy.R;
import com.example.xy.utils.Utils;

import java.util.List;



public class DropDownMenu extends LinearLayout {

    //顶部菜单布局
    private LinearLayout tabMenuView;
    //底部容器,包含popupMenuViews,maskView
    private FrameLayout containerView;
    //弹出菜单父布局
    private FrameLayout popupMenuViews;
    //遮罩半透明View,点击可关闭DropDownMenu
    private View maskView;
    //tabMenuView里面选中的tab位置,-1表示未选中
    private int current_tab_position = -1;

    //分割线颜色
    private int dividerColor = 0xffcccccc;
    //tab选中颜色
    private int textSelectedColor = 0xff890c85;
    //tab未选中颜色
    private int textUnselectedColor = 0xff111111;
    //遮罩颜色
    private int maskColor = 0x88888888;
    //tab字体大小
    private int menuTextSize = 14;

    //tab选中图标
    private int menuSelectedIcon;
    //tab未选中图标
    private int menuUnselectedIcon;

    private float menuHeighPercent = 0.5f;


    public DropDownMenu(Context context) {
        super(context, null);
    }

    public DropDownMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOrientation(VERTICAL);

        //为DropDownMenu添加自定义属性
        int menuBackgroundColor = 0xffffffff;
        int underlineColor = 0xffcccccc;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownMenu);
        underlineColor = a.getColor(R.styleable.DropDownMenu_ddunderlineColor, underlineColor);
        dividerColor = a.getColor(R.styleable.DropDownMenu_dddividerColor, dividerColor);
        textSelectedColor = a.getColor(R.styleable.DropDownMenu_ddtextSelectedColor, textSelectedColor);
        textUnselectedColor = a.getColor(R.styleable.DropDownMenu_ddtextUnselectedColor, textUnselectedColor);
        menuBackgroundColor = a.getColor(R.styleable.DropDownMenu_ddmenuBackgroundColor, menuBackgroundColor);
        maskColor = a.getColor(R.styleable.DropDownMenu_ddmaskColor, maskColor);
        menuTextSize = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddmenuTextSize, menuTextSize);
        menuSelectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddmenuSelectedIcon, menuSelectedIcon);
        menuUnselectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddmenuUnselectedIcon, menuUnselectedIcon);
        menuHeighPercent = a.getFloat(R.styleable.DropDownMenu_ddmenuMenuHeightPercent,menuHeighPercent);
        a.recycle();

        //初始化tabMenuView并添加到tabMenuView
        tabMenuView = new LinearLayout(context);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tabMenuView.setOrientation(HORIZONTAL);
        tabMenuView.setBackgroundColor(menuBackgroundColor);
        tabMenuView.setLayoutParams(params);
        addView(tabMenuView, 0);

        //为tabMenuView添加下划线
        View underLine = new View(getContext());
        underLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dpTpPx(1.0f)));
        underLine.setBackgroundColor(underlineColor);
        addView(underLine, 1);

        //初始化containerView并将其添加到DropDownMenu
        containerView = new FrameLayout(context);
        containerView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        addView(containerView, 2);

    }

    /**
     * 初始化DropDownMenu
     *
     * @param tabTexts
     * @param popupViews
     * @param contentView
     */
    public void setDropDownMenu(@NonNull List<String> tabTexts, @NonNull List<View> popupViews, @NonNull View contentView) {
        if (tabTexts.size() != popupViews.size()) {
            throw new IllegalArgumentException("params not match, tabTexts.size() should be equal popupViews.size()");
        }

        for (int i = 0; i < tabTexts.size(); i++) {
            addTab(tabTexts, i);
        }
        containerView.addView(contentView, 0);

        maskView = new View(getContext());
        maskView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        maskView.setBackgroundColor(maskColor);
        maskView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });
        containerView.addView(maskView, 1);
        maskView.setVisibility(GONE);
        if (containerView.getChildAt(2) != null){
            containerView.removeViewAt(2);
        }

        popupMenuViews = new FrameLayout(getContext());
        popupMenuViews.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (Utils.getScreenSize(getContext()).y*menuHeighPercent)));
        popupMenuViews.setVisibility(GONE);
        containerView.addView(popupMenuViews, 2);

        for (int i = 0; i < popupViews.size(); i++) {
            popupViews.get(i).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            popupMenuViews.addView(popupViews.get(i), i);
        }

    }

    private void addTab(@NonNull List<String> tabTexts, int i) {
        final TextView tab = new TextView(getContext());
        tab.setSingleLine();
        tab.setEllipsize(TextUtils.TruncateAt.END);
        tab.setGravity(Gravity.CENTER);
        tab.setTextSize(TypedValue.COMPLEX_UNIT_PX,menuTextSize);
        tab.setLayoutParams(new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
        tab.setTextColor(textUnselectedColor);
        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(menuUnselectedIcon), null);
        tab.setText(tabTexts.get(i));
        tab.setPadding(dpTpPx(5), dpTpPx(12), dpTpPx(5), dpTpPx(12));
        //添加点击事件
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchMenu(tab);
            }
        });
        tabMenuView.addView(tab);
        //添加分割线
        if (i < tabTexts.size() - 1) {
            View view = new View(getContext());
            view.setLayoutParams(new LayoutParams(dpTpPx(0.5f), ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(dividerColor);
            tabMenuView.addView(view);
        }
    }

    /**
     * 改变tab文字
     *
     * @param text
     */
    public void setTabText(String text) {
        if (current_tab_position != -1) {
            ((TextView) tabMenuView.getChildAt(current_tab_position)).setText(text);
        }
    }

    public void setTabClickable(boolean clickable) {
        for (int i = 0; i < tabMenuView.getChildCount(); i = i + 2) {
            tabMenuView.getChildAt(i).setClickable(clickable);
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        if (current_tab_position != -1) {
            ((TextView) tabMenuView.getChildAt(current_tab_position)).setTextColor(textUnselectedColor);
            ((TextView) tabMenuView.getChildAt(current_tab_position)).setCompoundDrawablesWithIntrinsicBounds(null, null,
                    getResources().getDrawable(menuUnselectedIcon), null);
            popupMenuViews.setVisibility(View.GONE);
            popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_out));
            maskView.setVisibility(GONE);
            maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_out));
            current_tab_position = -1;
        }

    }

    /**
     * DropDownMenu是否处于可见状态
     *
     * @return
     */
    public boolean isShowing() {
        return current_tab_position != -1;
    }

    /**
     * 切换菜单
     *
     * @param target
     */
    private void switchMenu(View target) {
        System.out.println(current_tab_position);
        for (int i = 0; i < tabMenuView.getChildCount(); i = i + 2) {
            if (target == tabMenuView.getChildAt(i)) {
                if (current_tab_position == i) {
                    closeMenu();
                } else {
                    if (current_tab_position == -1) {
                        popupMenuViews.setVisibility(View.VISIBLE);
                        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_in));
                        maskView.setVisibility(VISIBLE);
                        maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_in));
                        popupMenuViews.getChildAt(i / 2).setVisibility(View.VISIBLE);
                    } else {
                        popupMenuViews.getChildAt(i / 2).setVisibility(View.VISIBLE);
                    }
                    current_tab_position = i;
                    ((TextView) tabMenuView.getChildAt(i)).setTextColor(textSelectedColor);
                    ((TextView) tabMenuView.getChildAt(i)).setCompoundDrawablesWithIntrinsicBounds(null, null,
                            getResources().getDrawable(menuSelectedIcon), null);
                }
            } else {
                ((TextView) tabMenuView.getChildAt(i)).setTextColor(textUnselectedColor);
                ((TextView) tabMenuView.getChildAt(i)).setCompoundDrawablesWithIntrinsicBounds(null, null,
                        getResources().getDrawable(menuUnselectedIcon), null);
                popupMenuViews.getChildAt(i / 2).setVisibility(View.GONE);
            }
        }
    }

    public int dpTpPx(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }
}

使用:
kotlin

 /** 风格,销量,品质,价格*/
private var styleSelectAdapter = StyleSelectAdapter()
private var saleSelectAdapter = StyleSelectAdapter()
private var qualitySelectAdapter = StyleSelectAdapter()
private var priceSelectAdapter = StyleSelectAdapter()

/** 弹框1数据*/
private var styleList = mutableListOf<StyleSelectListData.Data>()
private var qualityList = mutableListOf<StyleSelectListData.Data>()
private var saleList = mutableListOf<StyleSelectListData.Data>()
private var priceList = mutableListOf<StyleSelectListData.Data>()
private val headers = arrayOf("区域", "风格", "阶段", "智能排序")
private var popupViews = mutableListOf<View>()

//以下内容是初始化每项的下拉框,每个下拉框都是一个RecyclerView

/* 风格 */
val styleView = me.layoutInflater.inflate(R.layout.view_drop_down_normal_select,null)
val recyclerStyleView = styleView.findViewById<RecyclerView>(R.id.list_rv)
recyclerStyleView.layoutManager = LinearLayoutManager(me)
recyclerStyleView.adapter = styleSelectAdapter

/* 销量 */
val saleView = me.layoutInflater.inflate(R.layout.view_drop_down_normal_select,null)
val recyclerSaleView = saleView.findViewById<RecyclerView>(R.id.list_rv)
recyclerSaleView.layoutManager = LinearLayoutManager(me)
recyclerSaleView.adapter = saleSelectAdapter

/* 品质 */
val qualityView = me.layoutInflater.inflate(R.layout.view_drop_down_normal_select,null)
val recyclerQualityView = qualityView.findViewById<RecyclerView>(R.id.list_rv)
recyclerQualityView.layoutManager = LinearLayoutManager(me)
recyclerQualityView.adapter = qualitySelectAdapter

/* 价格 */
val priceView = me.layoutInflater.inflate(R.layout.view_drop_down_normal_select,null)
val recyclerPriceView = priceView.findViewById<RecyclerView>(R.id.list_rv)
recyclerPriceView.layoutManager = LinearLayoutManager(me)
recyclerPriceView.adapter = priceSelectAdapter

popupViews.add(styleView)
popupViews.add(saleView)
popupViews.add(qualityView)
popupViews.add(priceView)

相关文章

  • 第十九谈:下拉菜单

    本节课我们来开始学习 Bootstrap 的提供的下拉菜单组件。 一.下拉菜单 下拉菜单组件依赖于 Popper....

  • Android下拉菜单组件

    前言:复制文件到工程,根据需要修改代码即可。 组件代码java 使用:kotlin

  • AutoCompleteTextView自动完成文本框

    XML属性 android:completionHint 下拉菜单标题android:completionT...

  • Bootstrap - 菜单1

    下拉菜单(基本用法)- 跳转页面 小伙伴们注意,在Bootstrap框架中的下拉菜单组件是一个独立的组件,根据不同...

  • Bootstrap(基础二)

    第5章 菜单、按钮及导航 一、下拉菜单 小伙伴们注意,在Bootstrap框架中的下拉菜单组件是一个独立的组件,根...

  • Vue中判断点击是否在组件外

    自己使用div模拟select,有如下需求: 组件获得焦点时,自动弹出下拉菜单 鼠标点击下拉菜单时,下拉菜单不能收...

  • 每周设计赏析 #9

    这周我们来讲讲一个常用组件的交互设计-下拉菜单 下拉菜单是最早的交互组件之一,几乎所有的web app都有用到,看...

  • android 组件化

    Android组件化项目地址:Android组件化项目AndroidModulePattern Android组件...

  • android Toolbar溢出菜单显示图标的问题

    做Android开发的都知道,在toolbar上加下拉菜单很简单,但是下拉菜单都是文字格式,并没图文模式,并且没有...

  • 2019-02-28随笔

    1、组件:栅格、布局、按钮、图标、面包屑、下拉菜单、导航菜单、分页、表单、日期组件、表格、树选择、文件上传、文字提...

网友评论

      本文标题:Android下拉菜单组件

      本文链接:https://www.haomeiwen.com/subject/fouhhdtx.html