@Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    getActivity().getMenuInflater().inflate(R.menu.menu_treeview, menu);

    AdapterView.AdapterContextMenuInfo adapterInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
    long id = adapterInfo.id;
    TreeNodeInfo<Long> nodeInfo = mTreeStateManager.getNodeInfo(id);

    if (nodeInfo.isWithChildren()) {
      if (nodeInfo.isExpanded()) {
        menu.findItem(R.id.context_menu_expand_item).setVisible(false);
        menu.findItem(R.id.context_menu_expand_all).setVisible(false);
      } else {
        menu.findItem(R.id.context_menu_collapse).setVisible(false);
      }
    } else {
      menu.findItem(R.id.context_menu_expand_item).setVisible(false);
      menu.findItem(R.id.context_menu_expand_all).setVisible(false);
      menu.findItem(R.id.context_menu_collapse).setVisible(false);
    }

    // hide delete because deleting is dangerous
    menu.findItem(R.id.context_menu_delete).setVisible(false);

    super.onCreateContextMenu(menu, v, menuInfo);
  }
 @Override
 public boolean onContextItemSelected(MenuItem item) {
   AdapterView.AdapterContextMenuInfo menuInfo =
       (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
   long id = menuInfo.id;
   if (item.getItemId() == R.id.context_menu_collapse) {
     mTreeStateManager.collapseChildren(id);
     return true;
   } else if (item.getItemId() == R.id.context_menu_expand_all) {
     mTreeStateManager.expandEverythingBelow(id);
     return true;
   } else if (item.getItemId() == R.id.context_menu_expand_item) {
     mTreeStateManager.expandDirectChildren(id);
     return true;
   } else if (item.getItemId() == R.id.context_menu_delete) {
     mTreeStateManager.removeNodeRecursively(id);
     return true;
   } else {
     return super.onContextItemSelected(item);
   }
 }
 private void collapseAll() {
   if (mTreeStateManager != null) mTreeStateManager.collapseChildren(null);
 }
 private void expandAll() {
   if (mTreeStateManager != null) mTreeStateManager.expandEverythingBelow(null);
 }