android 自定义Android菜单背景的代码
时间:2022-06-23 08:54:40
public class MenuEx extends Activity {
private static final String TAG = "android123";
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = new MenuInflater(getApplicationContext());
inflater.inflate(R.menu.options_menu, menu);
setMenuBackground();
return true;
}
关键代码就是重写Layout类的工厂方法onCreateView,这里对比绘制的View来替换系统中的
protected void setMenuBackground(){
Log.d(TAG, "开始设置菜单的的背景");
getLayoutInflater().setFactory( new Factory() {
@Override public View onCreateView ( String name, Context context, AttributeSet attrs ) {
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
//上面这句Android123提醒大家不能有改动,目前来看对于原生android目前这个packageName还没有变化
try {
LayoutInflater f = getLayoutInflater();
final View view = f.createView( name, null, attrs ); //尝试创建我们自己布局
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundResource( R.drawable.cwj"_bg); //设置背景为我们自定义的图片,替换cwj_bg文件即可 } } );
return view;
} catch (
InflateException e ) {}
catch (
ClassNotFoundException e ) {}
}
return null;
} }); }}
上面的例子可以轻松的替换当前Activity的Menu背景颜色,这里Android开发网再次提醒大家上面加粗的包名不能随意改动,如果非原生的Android系统,这句可能根据各个厂商编译的固件来灵活处理。
标签:菜单背景
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android编程获取GPS数据的方法详解
2023-09-20 16:37:34
![](https://img.aspxhome.com/file/2023/1/88721_0s.jpg)
基于JavaMail实现邮件发送
2022-06-21 02:28:06
Android自定义ListView实现下拉刷新上拉加载更多
2021-08-20 21:17:04
![](https://img.aspxhome.com/file/2023/0/125550_0s.gif)
C#移除字符串中的不可见Unicode字符 案例代码
2023-04-28 19:06:06
使用SpringBoot开发Restful服务实现增删改查功能
2023-01-20 05:17:29
![](https://img.aspxhome.com/file/2023/8/61658_0s.png)
Android实现老虎机小游戏代码示例
2022-08-04 04:15:11
![](https://img.aspxhome.com/file/2023/1/139451_0s.jpg)
Android实现带指示器的自动轮播式ViewPager
2022-07-25 22:28:49
![](https://img.aspxhome.com/file/2023/2/97852_0s.gif)
Java详解Swing中的几种常用按钮的使用
2023-12-04 21:44:30
![](https://img.aspxhome.com/file/2023/7/76197_0s.png)
详解Android通知栏沉浸式/透明化完整解决方案
2023-09-06 03:59:11
![](https://img.aspxhome.com/file/2023/2/100642_0s.gif)
Java矩阵连乘问题(动态规划)算法实例分析
2022-05-04 21:50:54
![](https://img.aspxhome.com/file/2023/8/65598_0s.jpg)
Android图片三级缓存开发
2023-12-03 22:42:43
java实现顺时针打印矩阵
2023-06-26 19:17:22
C#词法分析器之正则表达式的使用
2023-06-21 13:10:58
![](https://img.aspxhome.com/file/2023/2/66592_0s.png)
Java Spring Controller 获取请求参数的几种方法详解
2023-04-07 02:11:17
C#采用mouse_event函数实现模拟鼠标功能
2023-07-07 16:09:54
C语言指针的图文详解
2021-07-26 11:26:25
![](https://img.aspxhome.com/file/2023/9/125909_0s.png)
Java Swing 多线程加载图片(保证顺序一致)
2023-10-26 10:10:36
![](https://img.aspxhome.com/file/2023/0/65210_0s.jpg)
Spring 与 JDK 线程池的简单使用示例详解
2023-08-20 04:02:59
Java面试题解析之判断以及防止SQL注入
2023-05-26 18:08:59
基于C#实现简单的随机抽奖小程序
2023-07-14 10:15:50