1.类代码
package com.e.acationbar; import android.content.Context; import android.view.ActionProvider; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.SubMenu; import android.view.View; import android.widget.Toast; public class CustomActionProviderNoActionView extends ActionProvider implements OnMenuItemClickListener { private Context mContext; // 在选中悬浮菜单中的菜单时,菜单项默认执行的操作。 @Override public boolean onPerformDefaultAction() { // TODO Auto-generated method stub return super.onPerformDefaultAction(); } /** * 创建子菜单 * * @param subMenu */ @Override public void onPrepareSubMenu(SubMenu subMenu) { // TODO Auto-generated method stub subMenu.clear(); MenuInflater mif = new MenuInflater(mContext); mif.inflate(R.menu.provider_no_av, subMenu);// 通过菜单资源文件生成菜单 // 用代码添加子菜单 MenuItem mi = subMenu.add("用代码添加的菜单项"); mi.setIcon(R.drawable.actionbar_camera_icon); mi.setOnMenuItemClickListener(this); } /** * @return 返回true代表有子菜单 */ @Override public boolean hasSubMenu() { // TODO Auto-generated method stub return true; } @Override public boolean onMenuItemClick(MenuItem item) { // TODO Auto-generated method stub int id = item.getItemId(); Toast.makeText(mContext, "submenu " + id + "was clicked", Toast.LENGTH_SHORT).show(); return true; } @Override public View onCreateActionView() { // TODO Auto-generated method stub return null; } public CustomActionProviderNoActionView(Context context) { super(context); // TODO Auto-generated constructor stub mContext = context; } }
2.子菜单配置文件
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_share" android:actionProviderClass="android.widget.ShareActionProvider" android:icon="@drawable/actionbar_facefriend_icon" android:showAsAction="never" android:title="@string/share"> </item> <item android:id="@+id/action_custom_item" android:actionLayout="@layout/action_view_for_main" android:icon="@drawable/actionbar_particular_icon" android:showAsAction="ifRoom|collapseActionView" android:title="@string/action_custom_item"> </item> </menu>
3.这个provider在主菜单的中配置
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.e.acationbar.MainActivity" > <item android:id="@+id/action_customProvider_no_actionView" android:actionProviderClass="com.e.acationbar.CustomActionProviderNoActionView" android:icon="@drawable/actionbar_setting_icon" android:showAsAction="always" android:title="@string/custom_provider_no_av"> </item> ... </menu>
时间: 2024-10-09 09:51:23