实现带子菜单的选项菜单(Option Menu)

定义菜单资源

一个包含子菜单的菜单资源的例子如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.demo35.MainActivity" >

    <item
        android:id="@+id/change_bg"
        android:alphabeticShortcut="g"
        android:title="更换背景"/>
    <item
        android:id="@+id/change_settings"
        android:alphabeticShortcut="e"
        android:title="参数设置">
        <menu>
            <group android:checkableBehavior="all" >
                <item
                    android:id="@+id/use_bg"
                    android:title="使用背景"/>
                <item
                    android:id="@+id/bg_music"
                    android:title="背景音乐"/>
            </group>
        </menu>
    </item>
    <item
        android:id="@+id/change_default"
        android:alphabeticShortcut="r"
        android:title="恢复默认"/>

</menu>

在<item>元素中再包含<menu>元素可以创建包含子菜单的选项


创建菜单

在Activity 中的onCreateOptionsMenu() 方法可以初始化菜单资源

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


重写监听函数

重写Activity 中的onOptionsItemSelected() 方法:

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch(id){
		...
		}
		return true;
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值