Skip to content
Uwe Kubosch edited this page May 6, 2013 · 4 revisions

Our goal

Show spinner widget and update text label based on user selection. This example lists "ISO 3166" country code in the spinner, and show the full name for the user selected one.

Prerequisites

This tutorial has been tested with the following setups

Platform JDK ant Ruby ruboto jruby-jars Device API level
OS X 10.8.3 1.6.0_43 1.8.2 MRI 1.9.2 0.10.1 Nexus 7 android-10

Generate, install, and start your app

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

You should see an application called "Ruboto Spinner" in your application list on the device. You should eventually get "What hath Matz wrought?" and a button. Clicking the button displays a short notification (toast) "Flipped a bit via butterfly".

A fresh app

Code

Edit the file ruboto_spinner_activity.rb to this:

require 'ruboto/widget'

import 'android.widget.ArrayAdapter'
import 'java.util.Locale'

class RubotoSpinnerActivity
  def on_create(bundle)
    super
    set_title 'Ruboto Spinner Sample'
    self.setContentView(Ruboto::R::layout::activity_main)

    adapter = ArrayAdapter.new(self, Ruboto::R::layout::simplerow)
    adapter.add("")
    Locale.getISOCountries.each do |code|
      adapter.add(code)
    end

    spinner = findViewById(Ruboto::R::id::spinner)
    spinner.setAdapter(adapter)
    spinner.setPrompt("List of country codes")
    spinner.setOnItemSelectedListener(ItemSelectedListener.new(self))
  end
end

class ItemSelectedListener
  def initialize(activity)
    @activity = activity
  end

  def onItemSelected(spinner, view, position, id)
    if position != 0
      country_name = Locale.new("", spinner.getSelectedItem).getDisplayCountry(Locale::ENGLISH)
      label = @activity.findViewById(Ruboto::R::id::label)
      label.text = "Selected country is '#{country_name}'."
    end
  end
end

Create the file res/layout/activity_main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Spinner android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</LinearLayout>

Create the file res/layout/simplerow.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textColor="#000000"
  android:textSize="20sp">
</TextView>

Update and start the app

rake install start

It shows the spinner widget. If you change the selection, label is updated to show the country name.

Clone this wiki locally