android 创建菜单的心得

  最近做的音乐播放器中涉及到创建菜单。

  本来找到了类似于天天动听样子的菜单,但不适合我的,最后还用AlertDialog定义了一个菜单,不过还是把几种都写出来

 

  先来个天天动听式的菜单模式

 

package my.com.tabMenu;
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(context.getResources().getDrawable(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;
        }
    }
}


在你需要的创建菜单栏的Activity中编程如下代码

private TabMenu.MenuBodyAdapter []bodyAdapter=new TabMenu.MenuBodyAdapter[3];
    private TabMenu.MenuTitleAdapter titleAdapter;
    private TabMenu tabMenu;
    private int selTitle=0;

private void InitMenu()
    {
        //设置分页栏的标题
                titleAdapter = new TabMenu.MenuTitleAdapter(this, new String[] { "常用",
                        "设置", "工具" }, 16, 0xFF222222,Color.YELLOW,Color.WHITE);
                //定义每项分页栏的内容
                bodyAdapter[0]=new TabMenu.MenuBodyAdapter(this,new String[] { "添加歌曲", "清空列表","退出" }, 
                         new int[] { R.drawable.menu_refresh,R.drawable.next1,
                        R.drawable.menu_quit},13, 0xFFFFFFFF);
                 
                bodyAdapter[1]=new TabMenu.MenuBodyAdapter(this,new String[] { "设置1", "设置2",
                            "设置3"}, new int[] { R.drawable.menu_quit,
                            R.drawable.menu_downmanager, R.drawable.menu_help},13, 0xFFFFFFFF);
                 
                bodyAdapter[2]=new TabMenu.MenuBodyAdapter(this,new String[] { "工具1", "工具2",
                            "工具3", "工具4" }, new int[] { R.drawable.menu_quit,
                            R.drawable.menu_help, R.drawable.lastone,
                            R.drawable.menu_quit },13, 0xFFFFFFFF);
                 
                 
                tabMenu=new TabMenu(this,
                         new TitleClickEvent(),
                         new BodyClickEvent(),
                         titleAdapter,
                         R.color.darkblue,//TabMenu的背景颜色0x55123456
                         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.YELLOW);
            
            if(String.valueOf(selTitle).equals("0")&&String.valueOf(arg2).equals("2"))
                sysexit();
            if(String.valueOf(selTitle).equals("0")&&String.valueOf(arg2).equals("1"))
                {
                     clearlist();
                     tabMenu.dismiss();
                }
            if(String.valueOf(selTitle).equals("0")&&String.valueOf(arg2).equals("0"))
                {
                       Intent intent=new Intent();
                       intent.setClass(localActivity.this, refreshActivity.class);
                       startActivity(intent);
                }
            
        }
        
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {        
            sysexit();
        }
        else if(keyCode ==KeyEvent.KEYCODE_MENU)
        {
            if (tabMenu != null) {
                if (tabMenu.isShowing())
                    tabMenu.dismiss();
                else {
                    tabMenu.showAtLocation(findViewById(R.id.linr),
                            Gravity.BOTTOM, 0, 0);
                }
            }
        }
        return true;
    }

  便可创建一个类似天天动听的菜单效果

 第二个 用AlertDialog 定义菜单

package com.wjq.menu;


import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class CustomizeMenu extends Activity {
    
    private boolean isMore = false;// menu菜单翻页控制
    AlertDialog menuDialog;// menu菜单Dialog
    GridView menuGrid;
    View menuView;
    
    private final int ITEM_SEARCH = 0;// 搜索
    private final int ITEM_FILE_MANAGER = 1;// 文件管理
    private final int ITEM_DOWN_MANAGER = 2;// 下载管理
    private final int ITEM_FULLSCREEN = 3;// 全屏
    private final int ITEM_MORE = 11;// 菜单

    
    /** 菜单图片 **/
    int[] menu_image_array = { R.drawable.menu_search,
            R.drawable.menu_filemanager, R.drawable.menu_downmanager,
            R.drawable.menu_fullscreen, R.drawable.menu_inputurl,
            R.drawable.menu_bookmark, R.drawable.menu_bookmark_sync_import,
            R.drawable.menu_sharepage, R.drawable.menu_quit,
            R.drawable.menu_nightmode, R.drawable.menu_refresh,
            R.drawable.menu_more };
    /** 菜单文字 **/
    String[] menu_name_array = { "搜索", "文件管理", "下载管理", "全屏", "网址", "书签",
            "加入书签", "分享页面", "退出", "夜间模式", "刷新", "更多" };
    /** 菜单图片2 **/
    int[] menu_image_array2 = { R.drawable.menu_auto_landscape,
            R.drawable.menu_penselectmodel, R.drawable.menu_page_attr,
            R.drawable.menu_novel_mode, R.drawable.menu_page_updown,
            R.drawable.menu_checkupdate, R.drawable.menu_checknet,
            R.drawable.menu_refreshtimer, R.drawable.menu_syssettings,
            R.drawable.menu_help, R.drawable.menu_about, R.drawable.menu_return };
    /** 菜单文字2 **/
    String[] menu_name_array2 = { "自动横屏", "笔选模式", "阅读模式", "浏览模式", "快捷翻页",
            "检查更新", "检查网络", "定时刷新", "设置", "帮助", "关于", "返回" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        menuView = View.inflate(this, R.layout.gridview_menu, null);
        // 创建AlertDialog
        menuDialog = new AlertDialog.Builder(this).create();
        menuDialog.setView(menuView);
        menuDialog.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_MENU)// 监听按键
                    dialog.dismiss();
                return false;
            }
        });
        
        menuGrid = (GridView) menuView.findViewById(R.id.gridview);
        menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));
        /** 监听menu选项 **/
        menuGrid.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                switch (arg2) {
                case ITEM_SEARCH:// 搜索

                    break;
                case ITEM_FILE_MANAGER:// 文件管理

                    break;
                case ITEM_DOWN_MANAGER:// 下载管理

                    break;
                case ITEM_FULLSCREEN:// 全屏

                    break;
                case ITEM_MORE:// 翻页
                    if (isMore) {
                        menuGrid.setAdapter(getMenuAdapter(menu_name_array2,
                                menu_image_array2));
                        isMore = false;
                    } else {// 首页
                        menuGrid.setAdapter(getMenuAdapter(menu_name_array,
                                menu_image_array));
                        isMore = true;
                    }
                    menuGrid.invalidate();// 更新menu
                    menuGrid.setSelection(ITEM_MORE);
                    break;
                }
                
                
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");// 必须创建一项
        return super.onCreateOptionsMenu(menu);
    }
    
    private SimpleAdapter getMenuAdapter(String[] menuNameArray,
            int[] imageResourceArray) {
        ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < menuNameArray.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImage", imageResourceArray[i]);
            map.put("itemText", menuNameArray[i]);
            data.add(map);
        }
        SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
                R.layout.item_menu, new String[] { "itemImage", "itemText" },
                new int[] { R.id.item_image, R.id.item_text });
        return simperAdapter;
    }
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        // TODO Auto-generated method stub
        if (menuDialog == null) {
            menuDialog = new AlertDialog.Builder(this).setView(menuView).show();
        } else {
            menuDialog.show();
        }
        return false;// 返回为true 则显示系统menu
    }
}

 

利用PopupWindow  其中涉及到菜单的动画效果

package my.com.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

public class MenuBottmActivity extends Activity {
    /** Called when the activity is first created. */
        Animation showAction, hideAction; 
        LinearLayout menu; 
        Button button; 
        boolean menuShowed; 
        private GridView gv;
        
        private int[] icon={
                R.drawable.alarm,R.drawable.android,R.drawable.barcode_reader,
                R.drawable.bluetooth,R.drawable.browser,R.drawable.bump,
                R.drawable.calculator,R.drawable.camcorder,R.drawable.calendar};
        
        private String[] items={"浏览器","图片","相机","时钟","音乐","市场","拨号","信息","地图"};
        private PopupWindow popw;
        private View layout;
                
        @Override 
        public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
            
            menu = (LinearLayout) findViewById(R.id.menu); 
            button = (Button) findViewById(R.id.button); 
            
            
            
             // 这里是TranslateAnimation动画 
            showAction = new TranslateAnimation( 
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                     Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
              // 这里是ScaleAnimation动画 
            //showAction = new ScaleAnimation( 
            //    1.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
             showAction.setDuration(500); 

             // 这里是TranslateAnimation动画        
            hideAction = new TranslateAnimation( 
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                     Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
              // 这里是ScaleAnimation动画 
            //hideAction = new ScaleAnimation( 
            //        1.0f, 1.0f, 1.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
             hideAction.setDuration(500); 
            
            menuShowed = false; 
            menu.setVisibility(View.GONE); 
            
            button.setOnClickListener(new OnClickListener() { 

                @Override 
                public void onClick(View v) { 
                    // TODO Auto-generated method stub 
                    if (menuShowed) { 
                        menuShowed = false; 
                        menu.startAnimation(hideAction); 
                        menu.setVisibility(View.GONE); 
                    } 
                    else { 
                        menuShowed = true; 
                        menu.startAnimation(showAction); 
                        menu.setVisibility(View.VISIBLE); 
                    } 
                } 
                
            }); 
            
            //自定义菜单
            layout=LayoutInflater.from(MenuBottmActivity.this).inflate(R.layout.window, null);
            gv=(GridView)layout.findViewById(R.id.gv);
            
            gv.setAdapter(new Myadapter(MenuBottmActivity.this, icon, items));
            
            
        } 
        
        public boolean onKeyDown(int keyCode, KeyEvent event){
          //截获按键事件         
            if(keyCode == KeyEvent.KEYCODE_MENU){     
                
                InitPopupWindow(); 
                popw.showAtLocation(this.findViewById(R.id.button),                         
                        Gravity.CENTER, 0, 0);
                //在屏幕底部         
                }
            else if(keyCode == KeyEvent.KEYCODE_BACK){             
                if(popw.isShowing()){                 
                    popw.dismiss();             
                    }
                else{               
                    System.exit(0);
                    }         
                }         
            return false;         
        }
        
        public void InitPopupWindow()
        {
            if(popw==null)
            {
                popw=new PopupWindow(layout, 
                        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
                
            }
            if(popw.isShowing())
                popw.dismiss();
        }
        
        public class Myadapter extends BaseAdapter{
            private Context context;
            private int[] icon;
            private String[] items;
            public Myadapter(Context context,int[] icon,String[] items)
            {
                this.context=context;
                this.icon=icon;
                this.items=items;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return items.length;
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub
                convertView=LayoutInflater.from(context).inflate(R.layout.item_menu, null);
                TextView tv=(TextView)convertView.findViewById(R.id.item_text);
                ImageView image=(ImageView)convertView.findViewById(R.id.item_image);
                
                tv.setText(items[position]);
                image.setBackgroundResource(icon[position]);
                
                return convertView;
            }
            
        }
}


window.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:numColumns="3" >
</GridView>

menu_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout_Item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="5dip" >

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_centerHorizontal="true" >
    </ImageView>

    <TextView
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/item_image"
        android:layout_centerHorizontal="true"
        android:text="选项" >
    </TextView>

</RelativeLayout>

man.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/menu"
        android:layout_width="fill_parent"
        android:layout_height="100px"
        android:layout_alignParentTop="true"
        android:background="#ffffff" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="I am a menu" />
    </LinearLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Click to show/hide menu" />

</RelativeLayout>

 

 

posted @ 2012-06-29 16:15  慢~慢来  阅读(447)  评论(0编辑  收藏  举报