Adding submenus to the ActionProvider in Android



 


It is possible to show submenus with ActionProvider. In order to add submenus, we should override the onPrepareSubMenu(SubMenu subMenu) and hasSubMenu() methods. The resulting code of the should look like the following code block:


 


import android.app.Activity;


import android.content.Context;


import android.view.ActionProvider;


import android.view.LayoutInflater;


import android.view.MenuInflater;


import android.view.MenuItem;


import android.view.MenuItem.OnMenuItemClickListener;


import android.view.SubMenu;


import android.view.View;


import android.widget.ImageButton;


import android.widget.Toast;


public class Chapter1ActionProvider extends ActionProvider implements


OnMenuItemClickListener {


Context mContext;


public Chapter1ActionProvider(Context context) {


super(context);


mContext = context;


}


public View onCreateActionView() {


return null;


}


public boolean onPerformDefaultAction() {


Toast.makeText(mContext, \\\\\\\"Action Provider click\\\\\\\",


Toast.LENGTH_LONG).show();


return true;


}


public void onPrepareSubMenu(SubMenu subMenu) {


subMenu.clear();


subMenu.add(\\\\\\\"SubItem1\\\\\\\").setOnMenuItemClickListener(this);


subMenu.add(\\\\\\\"SubItem2\\\\\\\").setOnMenuItemClickListener(this);


}


public boolean onMenuItemClick(MenuItem item) {


Toast.makeText(mContext, \\\\\\\"Sub Item click\\\\\\\",


Toast.LENGTH_LONG).show();


return true;


}


public boolean hasSubMenu() {


return true;


}


}


 


In the onPrepareSubMenu(SubMenu subMenu) method, we dynamically created submenus and set their onMenuItemClickListener events. The onPrepareSubMenu(SubMenu subMenu) method is called if the hasSubMenu() method returns true, so we implemented it as returning true. It is also possible to create submenus from a menu XML file. If you want to create submenus from a menu XML file, onPrepareSubMenu(SubMenu subMenu) should look like the following code block:


public void onPrepareSubMenu(SubMenu subMenu) {


MenuInflater inflater = ((Activity)mContext).getMenuInflater();


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


}

Editor: ankita Added on: 2013-02-27 14:09:03 Total View:393







Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---