首页 > 其他分享 >Android提高第十八篇之自定义PopupWindow实现的Menu(TabMenu)

Android提高第十八篇之自定义PopupWindow实现的Menu(TabMenu)

时间:2023-05-01 14:02:23浏览次数:51  
标签:PopupWindow 自定义 int Menu TabMenu menu new import android


用过UCWEB-Android版的人都应该对其特殊的menu有印象,把menu做成Tab-Menu(支持分页的Menu),可以容纳比Android传统的menu更丰富的内容(Android的menu超过6项则缩略在[更多]里),本文参考网上的例子(作者:CoffeeCole,email:[email protected]),对例子进行简化以及封装,使其作为一个复合控件融入自己的framework。



先来看看本文程序运行的效果:





TabMenu本身就是一个PopupWindow,PopupWindow上面放了两个GridView,第一个GridView就是分页标签,位于PopupWindow的顶部,第二个GridView是菜单,位于PopupWindow的主体。为了实现PopupWindow的弹出/退出的动画效果,本文使用了以下代码:



在工程的res文件夹里添加anim子目录,再新建文件popup_enter.xml:

<?xml version="1.0" encoding="utf-8"?>  <set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="1000" />  
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />  
</set>



新建文件popup_exit.xml:


<?xml version="1.0" encoding="utf-8"?>  <set xmlns:android="http://schemas.android.com/apk/res/android">  
    <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="1000" />  
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="1000" />  
</set>



在工程的values文件夹里新建文件popup_animation.xml:



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

<resources>     

    <style name="PopupAnimation" parent="android:Animation"> 

        <item name="android:windowEnterAnimation">@anim/popup_enter</item>  

        <item name="android:windowExitAnimation">@anim/popup_exit</item>   

    </style>  

</resources>



main.xml的源码如下:


<?xml version="1.0" encoding="utf-8"?>  <LinearLayout android:id="@+id/LinearLayout01"  
    android:layout_width="fill_parent" android:layout_height="fill_parent"  
    xmlns:android="http://schemas.android.com/apk/res/android">  
    <TextView android:id="@+id/TextView01" android:layout_height="wrap_content"  
        android:layout_width="fill_parent" android:text="扩展Menu----hellogv"></TextView>  
</LinearLayout>



TabMenu的封装类TabMenu.java的源码如下:


package com.testTabMenu;  
import android.content.Context;  
import android.graphics.Color;  
import android.graphics.drawable.ColorDrawable;  
import android.view.Gravity;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.BaseAdapter;  
import android.widget.GridView;  
import android.widget.ImageView;  
import android.widget.LinearLayout;  
import android.widget.PopupWindow;  
import android.widget.TextView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.LinearLayout.LayoutParams;  
public class TabMenu extends PopupWindow{  
    private GridView gvBody, gvTitle;  
    private LinearLayout mLayout;  
    private MenuTitleAdapter titleAdapter;  
    public TabMenu(Context context,OnItemClickListener titleClick,OnItemClickListener bodyClick,  
            MenuTitleAdapter titleAdapter,int colorBgTabMenu,int aniTabMenu){  
        super(context);  
          
        mLayout = new LinearLayout(context);  
        mLayout.setOrientation(LinearLayout.VERTICAL);  
        //标题选项栏  
        gvTitle = new GridView(context);  
        gvTitle.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
        gvTitle.setNumColumns(titleAdapter.getCount());  
        gvTitle.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);  
        gvTitle.setVerticalSpacing(1);  
        gvTitle.setHorizontalSpacing(1);  
        gvTitle.setGravity(Gravity.CENTER);  
        gvTitle.setOnItemClickListener(titleClick);  
        gvTitle.setAdapter(titleAdapter);  
        gvTitle.setSelector(new ColorDrawable(Color.TRANSPARENT));//选中的时候为透明色  
        this.titleAdapter=titleAdapter;  
        //子选项栏  
        gvBody = new GridView(context);  
        gvBody.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));  
        gvBody.setSelector(new ColorDrawable(Color.TRANSPARENT));//选中的时候为透明色  
        gvBody.setNumColumns(4);  
        gvBody.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);  
        gvBody.setVerticalSpacing(10);  
        gvBody.setHorizontalSpacing(10);  
        gvBody.setPadding(10, 10, 10, 10);  
        gvBody.setGravity(Gravity.CENTER);  
        gvBody.setOnItemClickListener(bodyClick);  
        mLayout.addView(gvTitle);  
        mLayout.addView(gvBody);  
          
        //设置默认项  
        this.setContentView(mLayout);  
        this.setWidth(LayoutParams.FILL_PARENT);  
        this.setHeight(LayoutParams.WRAP_CONTENT);  
        this.setBackgroundDrawable(new ColorDrawable(colorBgTabMenu));// 设置TabMenu菜单背景  
        this.setAnimationStyle(aniTabMenu);  
        this.setFocusable(true);// menu菜单获得焦点 如果没有获得焦点menu菜单中的控件事件无法响应  
    }  
      
      
    public void SetTitleSelect(int index)  
    {  
        gvTitle.setSelection(index);  
        this.titleAdapter.SetFocus(index);  
    }  
      
    public void SetBodySelect(int index,int colorSelBody)  
    {  
        int count=gvBody.getChildCount();  
        for(int i=0;i<count;i++)  
        {  
            if(i!=index)  
                ((LinearLayout)gvBody.getChildAt(i)).setBackgroundColor(Color.TRANSPARENT);  
        }  
        ((LinearLayout)gvBody.getChildAt(index)).setBackgroundColor(colorSelBody);  
    }  
      
    public void SetBodyAdapter(MenuBodyAdapter bodyAdapter)  
    {  
        gvBody.setAdapter(bodyAdapter);  
    }  
      
    /** 
     * 自定义Adapter,TabMenu的每个分页的主体 
     *  
     */  
    static public class MenuBodyAdapter extends BaseAdapter {  
        private Context mContext;  
        private int fontColor,fontSize;  
        private String[] texts;  
        private int[] resID;  
        /** 
         * 设置TabMenu的分页主体 
         * @param context 调用方的上下文 
         * @param texts 按钮集合的字符串数组 
         * @param resID 按钮集合的图标资源数组 
         * @param fontSize 按钮字体大小 
         * @param color 按钮字体颜色 
         */  
        public MenuBodyAdapter(Context context, String[] texts,int[] resID, int fontSize,int fontColor)   
        {  
            this.mContext = context;  
            this.fontColor = fontColor;  
            this.texts = texts;  
            this.fontSize=fontSize;  
            this.resID=resID;  
        }  
        public int getCount() {  
            return texts.length;  
        }  
        public Object getItem(int position) {  
              
            return makeMenyBody(position);  
        }  
        public long getItemId(int position) {  
            return position;  
        }  
          
        private LinearLayout makeMenyBody(int position)  
        {  
            LinearLayout result=new LinearLayout(this.mContext);  
            result.setOrientation(LinearLayout.VERTICAL);  
            result.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);     
            result.setPadding(10, 10, 10, 10);  
              
            TextView text = new TextView(this.mContext);  
            text.setText(texts[position]);  
            text.setTextSize(fontSize);  
            text.setTextColor(fontColor);  
            text.setGravity(Gravity.CENTER);  
            text.setPadding(5, 5, 5, 5);  
            ImageView img=new ImageView(this.mContext);  
            img.setBackgroundResource(resID[position]);  
            result.addView(img,new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)));  
            result.addView(text);  
            return result;  
        }  
          
        public View getView(int position, View convertView, ViewGroup parent) {  
            return makeMenyBody(position);  
        }  
    }  
      
      
    /** 
     * 自定义Adapter,TabMenu的分页标签部分 
     *  
     */  
    static public class MenuTitleAdapter extends BaseAdapter {  
        private Context mContext;  
        private int fontColor,unselcolor,selcolor;  
        private TextView[] title;  
        /** 
         * 设置TabMenu的title 
         * @param context 调用方的上下文 
         * @param titles 分页标签的字符串数组 
         * @param fontSize 字体大小 
         * @param fontcolor 字体颜色 
         * @param unselcolor 未选中项的背景色 
         * @param selcolor 选中项的背景色 
         */  
        public MenuTitleAdapter(Context context, String[] titles, int fontSize,  
                int fontcolor,int unselcolor,int selcolor) {  
            this.mContext = context;  
            this.fontColor = fontcolor;  
            this.unselcolor = unselcolor;  
            this.selcolor=selcolor;  
            this.title = new TextView[titles.length];  
            for (int i = 0; i < titles.length; i++) {  
                title[i] = new TextView(mContext);  
                title[i].setText(titles[i]);  
                title[i].setTextSize(fontSize);  
                title[i].setTextColor(fontColor);  
                title[i].setGravity(Gravity.CENTER);  
                title[i].setPadding(10, 10, 10, 10);  
            }  
        }  
        public int getCount() {  
            return title.length;  
        }  
        public Object getItem(int position) {  
            return title[position];  
        }  
        public long getItemId(int position) {  
            return title[position].getId();  
        }  
        /** 
         * 设置选中的效果 
         */  
        private void SetFocus(int index)  
        {  
            for(int i=0;i<title.length;i++)  
            {  
                if(i!=index)  
                {  
                    title[i].setBackgroundDrawable(new ColorDrawable(unselcolor));//设置没选中的颜色  
                    title[i].setTextColor(fontColor);//设置没选中项的字体颜色  
                }  
            }  
            title[index].setBackgroundColor(0x00);//设置选中项的颜色  
            title[index].setTextColor(selcolor);//设置选中项的字体颜色  
        }  
          
        public View getView(int position, View convertView, ViewGroup parent) {  
            View v;  
            if (convertView == null) {  
                v = title[position];  
            } else {  
                v = convertView;  
            }  
            return v;  
        }  
    }  
}



testTabMenu介绍了数据的定义以及TabMenu的使用,源码如下:


package com.testTabMenu;  
import android.app.Activity;  
import android.graphics.Color;  
import android.os.Bundle;  
import android.view.Gravity;  
import android.view.Menu;  
import android.view.View;  
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.Toast;  
public class testTabMenu extends Activity {  
    TabMenu.MenuBodyAdapter []bodyAdapter=new TabMenu.MenuBodyAdapter[3];  
    TabMenu.MenuTitleAdapter titleAdapter;  
    TabMenu tabMenu;  
    int selTitle=0;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        //设置分页栏的标题  
        titleAdapter = new TabMenu.MenuTitleAdapter(this, new String[] { "常用",  
                "设置", "工具" }, 16, 0xFF222222,Color.LTGRAY,Color.WHITE);  
        //定义每项分页栏的内容  
        bodyAdapter[0]=new TabMenu.MenuBodyAdapter(this,new String[] { "常用1", "常用2", },   
                 new int[] { R.drawable.menu_test,  
                R.drawable.menu_bookmark},13, 0xFFFFFFFF);  
           
        bodyAdapter[1]=new TabMenu.MenuBodyAdapter(this,new String[] { "设置1", "设置2",  
                    "设置3"}, new int[] { R.drawable.menu_edit,  
                    R.drawable.menu_delete, R.drawable.menu_fullscreen},13, 0xFFFFFFFF);  
           
        bodyAdapter[2]=new TabMenu.MenuBodyAdapter(this,new String[] { "工具1", "工具2",  
                    "工具3", "工具4" }, new int[] { R.drawable.menu_copy,  
                    R.drawable.menu_cut, R.drawable.menu_normalmode,  
                    R.drawable.menu_quit },13, 0xFFFFFFFF);  
           
           
        tabMenu=new TabMenu(this,  
                 new TitleClickEvent(),  
                 new BodyClickEvent(),  
                 titleAdapter,  
                 0x55123456,//TabMenu的背景颜色  
                 R.style.PopupAnimation);//出现与消失的动画  
           
         tabMenu.update();  
         tabMenu.SetTitleSelect(0);  
         tabMenu.SetBodyAdapter(bodyAdapter[0]);  
    }  
      
    class TitleClickEvent implements OnItemClickListener{  
        @Override  
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
                long arg3) {  
            selTitle=arg2;  
            tabMenu.SetTitleSelect(arg2);  
            tabMenu.SetBodyAdapter(bodyAdapter[arg2]);  
        }  
    }  
      
    class BodyClickEvent implements OnItemClickListener{  
        @Override  
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
                long arg3) {  
            tabMenu.SetBodySelect(arg2,Color.GRAY);  
            String str="第"+String.valueOf(selTitle)+"栏\n\r"  
            +"第"+String.valueOf(arg2)+"项";  
            Toast.makeText(testTabMenu.this, str, 500).show();  
              
        }  
          
    }  
    @Override  
    /** 
     * 创建MENU 
     */  
    public boolean onCreateOptionsMenu(Menu menu) {  
        menu.add("menu");// 必须创建一项  
        return super.onCreateOptionsMenu(menu);  
    }  
    @Override  
    /** 
     * 拦截MENU 
     */  
    public boolean onMenuOpened(int featureId, Menu menu) {  
        if (tabMenu != null) {  
            if (tabMenu.isShowing())  
                tabMenu.dismiss();  
            else {  
                tabMenu.showAtLocation(findViewById(R.id.LinearLayout01),  
                        Gravity.BOTTOM, 0, 0);  
            }  
        }  
        return false;// 返回为true 则显示系统menu  
    }  
      
}


  • Android提高第十八篇之自定义PopupWindow实现的Menu(TabMenu)_android

  • 大小: 529.3 KB
  • 查看图片附件

标签:PopupWindow,自定义,int,Menu,TabMenu,menu,new,import,android
From: https://blog.51cto.com/u_5454003/6238875

相关文章

  • 【web 开发基础】PHP自定义回调函数之call_user_func_array()
    前言从上一篇文章中我们了解到,回调函数是将一个函数作为参数传递到调用的函数中。如果在函数的格式说明中出现callback类型的参数,则该函数就是回调函数。虽然可以使用变量函数去声明自己的回调函数,不过我们通常大多还是会通过借助 call_user_func_array() 函数去实现。通过借助......
  • 自定义快捷键
    问题:复制粘贴的快捷键是CtrlC和CtrlV,在现实中粘贴值到可见单元格的用处更大,如何将这一功能自定义成快捷键?解决:【文件】》【选项】》【自定义功能区】 输入命令“粘贴值”,点击【请按新快捷键】,依次按下指定的快捷键(假设为Ctrl+Shift+V),点击【指定】 据此法,可以自定义任意命......
  • Excel 使用VBA 自定义函数
     启用Excel开发工具    打开Excel的VBA(ALT+F11)   新键VBA工程模块写入自定义函数FunctionHexIPAddr(strIPAddrAsString,isAscAsBoolean)AsStringDimarry,bit0AsString,bit1AsString,bit2AsString,bit3As......
  • Typora自定义图片图床服务器
    0x01启用picgo文件-偏好设置-图像-上传服务设定-PicGo-core(commandline)0x02安装插件打开路径C:\Users\你的用户名\.picgo(其他环境自己百度吧,我这是Windows),然后输入命令(得确保PC已有Node环境,不然npm报没有命令):npminstallpicgo-plugin-web-uploader0x02服务器返回接......
  • chipyard——自定义配置生成和前仿
    一,生成配置前面用rocket-chip仓库做了生成和前仿,为了方便扩展外设,这里转到chipyard仓库。首先我们生成一个之前用的配置: 为删SimDTM(我的测试框架不需要),先在rocket的subsystem/config下创建一个class: 然后在chipyard顶层创建config: makeCONFIG=MyConfig创建设计 发......
  • nginx自定义指定加载配置
    进入 /usr/local/nginx/conf/include目录,创建 nginx.node.conf文件,在里面输入如下代码:upstreamnodejs{server127.0.0.1:3000;#server127.0.0.1:3001;keepalive64;}server{listen80;server_namewww.penguu.compenguu.com;access_lo......
  • 如何自定义starter
    背景使用过SpringBoot的小伙伴都应该知道,一个SpringBoot项目就是由一个一个starter组成的,一个starter代表该项目的SpringBoot启动依赖,除了官方已有的starter,我们可以根据自己的需要自定义新的starter。我们经常会看到或者使用到各种***-starter。比如下面几种:spring-boo......
  • Ext.ux.TabCloseMenu插件的使用(TabPanel右键关闭菜单) 示例
    Ext.ux.TabCloseMenu插件的使用(TabPanel右键关闭菜单)示例效果: 创建调用的HTML:<html><head><metahttp-equiv="Content-Type"content="text/html;charset=GBK"/><title></title><linkrel="stylesheet"type="tex......
  • Spring 实现自定义 bean 的扩展
    Springmvc提供了扩展xml的机制,用来编写自定义的xmlbean,例如dubbo框架,就利用这个机制实现了好多的dubbobean,比如 <dubbo:application>、<dubbo:registry> 等等,只要安装这个标准的扩展方式实现配置即可。扩展自定义bean的意义何在假设我们要使用一个开源框架或者一套......
  • vue3自定义指令实现el-select下拉加载更多
    1.新建js文件exportdefault(app)=>{app.directive('loadmore',{beforeMount(el,binding){constelement=el.querySelector('.t-select__dropdown');element.addEventListener('scroll',()=>{co......