android 自定义menu背景,Android编程实现自定义系统菜单背景的方法

本文实例讲述了Android编程实现自定义系统菜单背景的方法。分享给大家供大家参考,具体如下:

不多说,上图,见代码。

9e8fb51e5e63390bc386b7b01e2c5d9a.png

package lab.sodino.menutest;

import android.content.Context;

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.util.AttributeSet;

import android.view.InflateException;

import android.view.LayoutInflater;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.view.View;

import android.widget.Toast;

/**

* @author Sodino E-mail:sodinoopen@hotmail.com

* @version Time:2011-1-26 下午04:42:04

*/

public class MenuAct extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

public boolean onCreateOptionsMenu(Menu menu) {

super.onCreateOptionsMenu(menu);

MenuInflater inflater = new MenuInflater(getApplicationContext());

inflater.inflate(R.menu.menu, menu);

setMenuBackground();

return true;

}

public boolean onOptionsItemSelected(MenuItem item) {

String info = "";

switch (item.getItemId()) {

case R.id.menu_add:

info = "Add";

break;

case R.id.menu_delete:

info = "Delete";

break;

case R.id.menu_home:

info = "Home";

break;

case R.id.menu_help:

info = "Help";

break;

default:

info = "NULL";

break;

}

Toast toast = Toast.makeText(this, info, Toast.LENGTH_SHORT);

toast.show();

return super.onOptionsItemSelected(item);

}

// 关键代码为重写Layout.Factory.onCreateView()方法自定义布局

protected void setMenuBackground() {

MenuAct.this.getLayoutInflater().setFactory(new android.view.LayoutInflater.Factory() {

/**

* name - Tag name to be inflated.

* context - The context the view is being created in.

* attrs - Inflation attributes as specified in XML file.

*/

public View onCreateView(String name, Context context, AttributeSet attrs) {

// 指定自定义inflate的对象

if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {

try {

LayoutInflater f = getLayoutInflater();

final View view = f.createView(name, null, attrs);

new Handler().post(new Runnable() {

public void run() {

// 设置背景图片

view.setBackgroundResource(R.drawable.menu_background);

}

});

return view;

} catch (InflateException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

return null;

}

});

}

}

/res/menu/menu.xml

希望本文所述对大家Android程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值