自定义一个MyActionProvider类,继承v4包下的ActionProvider(使用兼容Theme)
重写hasSubMenu(),返回true
重写onPrepareSubMenu()方法,设置submenu的title、icon、点击事件
package com.example.actionbartest.utils; import android.R; import android.content.Context; import android.support.v4.view.ActionProvider; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.SubMenu; import android.view.View; import android.widget.Toast; /** * 写一个带有自定义下拉submenu的ActionProvider * @author Frank * */ public class MyActionProvider extends ActionProvider { public MyActionProvider(Context context) { super(context); // TODO Auto-generated constructor stub } @Override public View onCreateActionView() { // TODO Auto-generated method stub return null; } /** * 重写hasSubMenu,返回true。 */ @Override public boolean hasSubMenu() { // TODO Auto-generated method stub return true; } @Override public void onPrepareSubMenu(SubMenu subMenu) { // TODO Auto-generated method stub subMenu.clear(); subMenu.add("sub title").setIcon(R.drawable.ic_dialog_email).setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // TODO Auto-generated method stub Toast.makeText(getContext(), "this is sub1", Toast.LENGTH_SHORT).show(); return true; } }); subMenu.add("sub title2").setIcon(R.drawable.ic_dialog_map).setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // TODO Auto-generated method stub Toast.makeText(getContext(), "this is sub2", Toast.LENGTH_SHORT).show(); return true; } }); } }
4、在menu.xml中注册item
<item android:id="@+id/action_show" android:icon="@drawable/ic_action_alarms" android:title="Show" app:actionProviderClass= "com.example.actionbartest.utils.MyActionProvider" app:showAsAction="always"/>
这样就简单的设置了一个ActionProvier,点击会出现两个subtitle