Android 自定义菜单

Android 自定义菜单
分类: android应用开发 1328人阅读 评论(0) 收藏 举报

       Android2.2版本中,如果你要修改菜单默认的背景颜色,网络上有许多的方法。在此就不说了。但是,如果要在2.2以上的版本修改菜单的样式,例如修改背景颜色,图片等,使用这些方法是没有任何作用的。因此自己写了一个自定义的菜单控件,可以自由定义菜单的样式,使得菜单的样式更加丰富。本文参考了这篇文章而写的:http://blog.csdn.net/hellogv/article/details/6168439


程序运行效果:


MyMenu本身是一个PopupWindow,PopupWindow上放了一个GridView。给GridView配了一个MyMenuAdapter,于是有了菜单的样子。


1: 在工程的res文件夹下添加目录anim子目录,在anim文件夹中,新建了两个文件:

popup_enter.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="500"/>  
  5.     <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500"/>  
  6.   
  7. </set>  
<?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="500"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500"/>

</set>
popup_exit.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <set xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="1000"/>  
  5.     <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="1000"/>  
  6.   
  7. </set>  
<?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>

2: 在工程的values文件夹下新建popup_animation.xml文件。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="PopupAnimation" parent="android:Animation">  
  4.         <item name="android:windowEnterAnimation">@anim/popup_enter</item>  
  5.         <item name="android:windowExitAnimation">@anim/popup_exit</item>  
  6.     </style>  
  7.       
  8. </resources>  
<?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>

3: main.xml代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical"   
  6.     android:id="@+id/linearLayout01">  
  7.   
  8.     <TextView  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/hello" />  
  12.   
  13. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:id="@+id/linearLayout01">

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

</LinearLayout>

4: MyMenu的源码如下:

  1. package com.haozi.demo.menu3.wiget;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Color;  
  5. import android.graphics.drawable.ColorDrawable;  
  6. import android.view.Gravity;  
  7. import android.view.KeyEvent;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.view.ViewGroup.LayoutParams;  
  11. import android.widget.BaseAdapter;  
  12. import android.widget.GridView;  
  13. import android.widget.LinearLayout;  
  14. import android.widget.PopupWindow;  
  15. import android.widget.TextView;  
  16. import android.widget.AdapterView.OnItemClickListener;  
  17.   
  18. /** 
  19.  * 我的菜单 
  20.  * @author haozi 
  21.  * 
  22.  */  
  23. public class MyMenu extends PopupWindow {  
  24.   
  25.     private GridView gvTitle;                 // 标题   
  26.     private LinearLayout mLayout;             // PopupWindow的布局   
  27.     private MyMenuAdapter myMenuAdapter;      // 自定义菜单的适配器   
  28.       
  29.     /** 
  30.      * 构造方法 
  31.      * @param context 调用方的上下文 
  32.      * @param titleClick 菜单点击事件 
  33.      * @param myMenuAdapter 菜单适配器 
  34.      * @param myMenuBackgroundColor 菜单背景颜色 
  35.      * @param myMenuAnim 菜单需要的动画效果 
  36.      */  
  37.     public MyMenu(Context context, OnItemClickListener titleClick,   
  38.             int myMenuBackgroundColor, int myMenuAnim){  
  39.         super(context);  
  40.           
  41.         // 创建适配器   
  42.         myMenuAdapter = new MyMenuAdapter(context,   
  43.                 new String[]{"目录""书签""摘要""设置"},   
  44.                 16,   
  45.                 Color.argb(25513910647),  // 未选中字体颜色   
  46.                 Color.argb(255247246234), // 选中字体颜色   
  47.                 Color.argb(255247246234), // 未选中背景颜色   
  48.                 Color.argb(25513910647)); // 选中背景颜色   
  49.           
  50.         mLayout = new LinearLayout(context);  
  51.         mLayout.setOrientation(LinearLayout.VERTICAL);  
  52.         // 菜单选项栏   
  53.         gvTitle = new GridView(context);  
  54.         gvTitle.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
  55.         // 设置列数   
  56.         gvTitle.setNumColumns(myMenuAdapter.getCount());  
  57.         // 设置宽度自适应   
  58.         gvTitle.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);  
  59.         gvTitle.setVerticalSpacing(1);  
  60.         gvTitle.setHorizontalSpacing(1);  
  61.         gvTitle.setGravity(Gravity.CENTER);  
  62.         gvTitle.setOnItemClickListener(titleClick);  
  63.         // 选中的时候为透明色   
  64.         gvTitle.setSelector(new ColorDrawable(Color.TRANSPARENT));  
  65.         gvTitle.setAdapter(myMenuAdapter);  
  66.         // 把gvTitle放在layout上   
  67.         this.mLayout.addView(gvTitle);  
  68.           
  69.         // 设置菜单的特征   
  70.         setContentView(this.mLayout);  
  71.         setWidth(LayoutParams.FILL_PARENT);  
  72.         setHeight(LayoutParams.WRAP_CONTENT);  
  73.         setBackgroundDrawable(new ColorDrawable(myMenuBackgroundColor));  
  74.         setAnimationStyle(myMenuAnim);  
  75.         setFocusable(true);  
  76.           
  77.         mLayout.setFocusableInTouchMode(true);  
  78.         mLayout.setOnKeyListener(new View.OnKeyListener() {  
  79.               
  80.             @Override  
  81.             public boolean onKey(View v, int keyCode, KeyEvent event) {  
  82.                   
  83.                 if(keyCode == KeyEvent.KEYCODE_MENU && isShowing()){  
  84.                     dismiss();  
  85.                     return true;  
  86.                 }  
  87.                 return false;  
  88.             }  
  89.         });  
  90.     }  
  91.       
  92.     public void setTitleSelect(int index)    
  93.     {    
  94.         gvTitle.setSelection(index);    
  95.         this.myMenuAdapter.setFocus(index);    
  96.     }     
  97.       
  98.     /** 
  99.      * 适配器 
  100.      * @author haozi 
  101.      * 
  102.      */  
  103.     class MyMenuAdapter extends BaseAdapter{  
  104.   
  105.         private Context context;  
  106.         private TextView[] tvTitles;  
  107.         private int fontUnSelColor;  
  108.         private int fontSelColor;  
  109.         private int bgUnSelColor;  
  110.         private int bgSelColor;  
  111.           
  112.         /** 
  113.          * 设置 title 
  114.          * @param context 调用方的上下文 
  115.          * @param titles 数据 
  116.          * @param fontSize 字体大小 
  117.          * @param fontUnSelColor 未选中字体颜色 
  118.          * @param fontSelColor 选中字体颜色 
  119.          * @param bgUnSelColor 未选中背景颜色 
  120.          * @param bgSelColor 选中背景颜色 
  121.          */  
  122.         public MyMenuAdapter(Context context, String[] titles,  
  123.                 int fontSize, int fontUnSelColor, int fontSelColor, int bgUnSelColor, int bgSelColor){  
  124.             this.context = context;  
  125.             this.fontUnSelColor = fontUnSelColor;  
  126.             this.fontSelColor = fontSelColor;  
  127.             this.bgUnSelColor = bgUnSelColor;  
  128.             this.bgSelColor = bgSelColor;  
  129.             // 根据传递进来的titles创建menu上的textView。   
  130.             tvTitles = new TextView[titles.length];  
  131.             for(int i=0; i<titles.length; i++){  
  132.                 tvTitles[i] = new TextView(context);  
  133.                 tvTitles[i].setText(titles[i]);  
  134.                 tvTitles[i].setTextSize(fontSize);  
  135.                 tvTitles[i].setTextColor(fontUnSelColor);  
  136.                 tvTitles[i].setGravity(Gravity.CENTER);  
  137.                 tvTitles[i].setPadding(10301030);  
  138.             }  
  139.         }  
  140.           
  141.         @Override  
  142.         public int getCount() {  
  143.             // TODO Auto-generated method stub   
  144.             return tvTitles.length;  
  145.         }  
  146.   
  147.         @Override  
  148.         public Object getItem(int position) {  
  149.             // TODO Auto-generated method stub   
  150.             return tvTitles[position];  
  151.         }  
  152.   
  153.         @Override  
  154.         public long getItemId(int position) {  
  155.             // TODO Auto-generated method stub   
  156.             return tvTitles[position].getId();  
  157.         }  
  158.           
  159.         /** 
  160.          * 设置选中效果 
  161.          * 
  162.          * @param index 
  163.          *  
  164.          * @project: 
  165.          * 
  166.          * @author haozi on 2012-3-5 
  167.          */  
  168.         public void setFocus(int index){  
  169.               
  170.             for(int i=0; i<tvTitles.length; i++){  
  171.                   
  172.                 if(i != index){// 如果未选中   
  173.                     this.tvTitles[i].setBackgroundColor(this.bgUnSelColor);  
  174.                     this.tvTitles[i].setTextColor(this.fontUnSelColor);  
  175.                 }else{// 如果选中   
  176.                     this.tvTitles[i].setBackgroundColor(this.bgSelColor);  
  177.                     this.tvTitles[i].setTextColor(this.fontSelColor);                     
  178.                 }  
  179.             }  
  180.         }  
  181.   
  182.         @Override  
  183.         public View getView(int position, View convertView, ViewGroup parent) {  
  184.               
  185.             View v = null;  
  186.             if(convertView == null){  
  187.                 v = tvTitles[position];  
  188.             }else{  
  189.                 v = convertView;  
  190.             }  
  191.             return v;  
  192.         }  
  193.     }  
  194. }  
package com.haozi.demo.menu3.wiget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 我的菜单
 * @author haozi
 *
 */
public class MyMenu extends PopupWindow {

	private GridView gvTitle;                 // 标题
	private LinearLayout mLayout;             // PopupWindow的布局
	private MyMenuAdapter myMenuAdapter;      // 自定义菜单的适配器
	
	/**
	 * 构造方法
	 * @param context 调用方的上下文
	 * @param titleClick 菜单点击事件
	 * @param myMenuAdapter 菜单适配器
	 * @param myMenuBackgroundColor 菜单背景颜色
	 * @param myMenuAnim 菜单需要的动画效果
	 */
	public MyMenu(Context context, OnItemClickListener titleClick, 
			int myMenuBackgroundColor, int myMenuAnim){
		super(context);
		
		// 创建适配器
		myMenuAdapter = new MyMenuAdapter(context, 
				new String[]{"目录", "书签", "摘要", "设置"}, 
				16, 
				Color.argb(255, 139, 106, 47),  // 未选中字体颜色
				Color.argb(255, 247, 246, 234), // 选中字体颜色
				Color.argb(255, 247, 246, 234), // 未选中背景颜色
				Color.argb(255, 139, 106, 47)); // 选中背景颜色
		
		mLayout = new LinearLayout(context);
		mLayout.setOrientation(LinearLayout.VERTICAL);
		// 菜单选项栏
		gvTitle = new GridView(context);
		gvTitle.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		// 设置列数
		gvTitle.setNumColumns(myMenuAdapter.getCount());
		// 设置宽度自适应
		gvTitle.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		gvTitle.setVerticalSpacing(1);
		gvTitle.setHorizontalSpacing(1);
		gvTitle.setGravity(Gravity.CENTER);
		gvTitle.setOnItemClickListener(titleClick);
		// 选中的时候为透明色
		gvTitle.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gvTitle.setAdapter(myMenuAdapter);
		// 把gvTitle放在layout上
		this.mLayout.addView(gvTitle);
		
		// 设置菜单的特征
		setContentView(this.mLayout);
		setWidth(LayoutParams.FILL_PARENT);
		setHeight(LayoutParams.WRAP_CONTENT);
		setBackgroundDrawable(new ColorDrawable(myMenuBackgroundColor));
		setAnimationStyle(myMenuAnim);
		setFocusable(true);
		
        mLayout.setFocusableInTouchMode(true);
        mLayout.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				
				if(keyCode == KeyEvent.KEYCODE_MENU && isShowing()){
					dismiss();
					return true;
				}
				return false;
			}
		});
	}
	
    public void setTitleSelect(int index)  
    {  
        gvTitle.setSelection(index);  
        this.myMenuAdapter.setFocus(index);  
    } 	
	
	/**
	 * 适配器
	 * @author haozi
	 *
	 */
	class MyMenuAdapter extends BaseAdapter{

		private Context context;
		private TextView[] tvTitles;
		private int fontUnSelColor;
		private int fontSelColor;
		private int bgUnSelColor;
		private int bgSelColor;
		
		/**
		 * 设置 title
		 * @param context 调用方的上下文
		 * @param titles 数据
		 * @param fontSize 字体大小
		 * @param fontUnSelColor 未选中字体颜色
		 * @param fontSelColor 选中字体颜色
		 * @param bgUnSelColor 未选中背景颜色
		 * @param bgSelColor 选中背景颜色
		 */
		public MyMenuAdapter(Context context, String[] titles,
				int fontSize, int fontUnSelColor, int fontSelColor, int bgUnSelColor, int bgSelColor){
			this.context = context;
			this.fontUnSelColor = fontUnSelColor;
			this.fontSelColor = fontSelColor;
			this.bgUnSelColor = bgUnSelColor;
			this.bgSelColor = bgSelColor;
			// 根据传递进来的titles创建menu上的textView。
			tvTitles = new TextView[titles.length];
			for(int i=0; i<titles.length; i++){
				tvTitles[i] = new TextView(context);
				tvTitles[i].setText(titles[i]);
				tvTitles[i].setTextSize(fontSize);
				tvTitles[i].setTextColor(fontUnSelColor);
				tvTitles[i].setGravity(Gravity.CENTER);
				tvTitles[i].setPadding(10, 30, 10, 30);
			}
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return tvTitles.length;
		}

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

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return tvTitles[position].getId();
		}
		
		/**
		 * 设置选中效果
		 *
		 * @param index
		 * 
		 * @project:
		 *
		 * @author haozi on 2012-3-5
		 */
		public void setFocus(int index){
			
			for(int i=0; i<tvTitles.length; i++){
				
				if(i != index){// 如果未选中
					this.tvTitles[i].setBackgroundColor(this.bgUnSelColor);
					this.tvTitles[i].setTextColor(this.fontUnSelColor);
				}else{// 如果选中
					this.tvTitles[i].setBackgroundColor(this.bgSelColor);
					this.tvTitles[i].setTextColor(this.fontSelColor);					
				}
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View v = null;
			if(convertView == null){
				v = tvTitles[position];
			}else{
				v = convertView;
			}
			return v;
		}
	}
}

5: demo的Activity的源码如下,是在这里创建MyMenu。

  1. /** 
  2.  * 入口Activity 
  3.  * @author haozi 
  4.  * 
  5.  */  
  6. public class _04MyMenuDemo3Activity extends Activity {  
  7.       
  8.     private MyMenu myMenu;  
  9.     private int setTitle;  
  10.       
  11.     @Override  
  12.     public void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);  
  15.           
  16.         myMenu = new MyMenu(this,   
  17.                 new TitleClickEvent(),   
  18.                 Color.argb(25513910647),   
  19.                 R.style.PopupAnimation);  
  20.           
  21.         myMenu.update();  
  22.         myMenu.setTitleSelect(0);  
  23.     }  
  24.       
  25.     class TitleClickEvent implements OnItemClickListener{    
  26.           
  27.         @Override    
  28.         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,    
  29.                 long arg3) {    
  30.             setTitle=arg2;    
  31.             myMenu.setTitleSelect(setTitle);  
  32.         }  
  33.     }   
  34.       
  35.     @Override  
  36.     public boolean onCreateOptionsMenu(Menu menu) {  
  37.           
  38.         menu.add("menu");  
  39.         return super.onCreateOptionsMenu(menu);  
  40.     }  
  41.       
  42.     @Override  
  43.     public boolean onMenuOpened(int featureId, Menu menu) {  
  44.           
  45.         if (myMenu != null) {    
  46.             if (myMenu.isShowing())    
  47.                 myMenu.dismiss();    
  48.             else {    
  49.                 myMenu.showAtLocation(findViewById(R.id.linearLayout01),    
  50.                         Gravity.BOTTOM, 00);    
  51.             }    
  52.         }    
  53.         return false;// 返回为true 则显示系统menu     
  54.     }  
  55. }  
/**
 * 入口Activity
 * @author haozi
 *
 */
public class _04MyMenuDemo3Activity extends Activity {
    
	private MyMenu myMenu;
	private int setTitle;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myMenu = new MyMenu(this, 
        		new TitleClickEvent(), 
        		Color.argb(255, 139, 106, 47), 
        		R.style.PopupAnimation);
        
        myMenu.update();
        myMenu.setTitleSelect(0);
    }
    
    class TitleClickEvent implements OnItemClickListener{  
    	
        @Override  
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
                long arg3) {  
        	setTitle=arg2;  
        	myMenu.setTitleSelect(setTitle);
        }
    } 
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
    	menu.add("menu");
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
    	
        if (myMenu != null) {  
            if (myMenu.isShowing())  
            	myMenu.dismiss();  
            else {  
            	myMenu.showAtLocation(findViewById(R.id.linearLayout01),  
                        Gravity.BOTTOM, 0, 0);  
            }  
        }  
        return false;// 返回为true 则显示系统menu  
    }
}

demo下载链接地址: http://download.csdn.net/detail/hello_haozi/4291200
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值