Tutorial: add a context menu

rystraum edited this page Jan 19, 2013 · 12 revisions

Goal

Add a long click context menu to a newly generated app.

Prerequisites

You should have completed the Getting started with Ruboto tutorial. You can use an android device or the emulator to run your app.

This tutorial has been tested on the following configurations

Platform JDK ant Ruby ruboto RubotoCore Device API level Tester
OS X 10.8.2 1.7.0_10 1.8.2 MRI 1.8.7 0.10.1 0.5.2 Samsung Galaxy S3 android-15 donv
Ubuntu 12.04.1 1.6.0_24 1.8.2 JRuby 1.7.2 0.10.1 0.5.2 Lenovo P700 android-15 rystraum

Create the app and run it

ruboto gen app --package org.ruboto.examples.context_menu_example
cd context_menu_example
rake install start

You should now see the familiar "What hath Matz wrought?".

!https://github.com/ruboto/ruboto/raw/master/examples/screen_shot_fresh_app.png(A fresh app)!

Add the menu

Add a callback for opening the menu. Edit the src/context_menu_example_activity.rb, and add the following method before the private statement:

def onCreateContextMenu(menu, v, menuInfo)
  super
  # menu.header_title = 'Context Menu' # temporarily commented as it causes no method errors in some installations
  menu.add(0, v.id, 0, 'Action 1').setOnMenuItemClickListener do |menu_item|
    @text_view.text = menu_item.title
    toast menu_item.title
    true # Prevent other listeners from executing.
  end
  menu.add(0, v.id, 0, 'Action 2').setOnMenuItemClickListener do |menu_item|
    @text_view.text = menu_item.title
    toast menu_item.title
    true # Prevent other listeners from executing.
  end
end

Enable the context menu for the button

Add the following line to the end of the on_createmethod, just before the rescue block:

registerForContextMenu(findViewById(43))

Redeploy your app

rake install start

After your app restarts, you should be able to long press the button to display a context menu. Selecting any of the menu items should pop up a toast with the title of the menu item.

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.