Sunday, December 30, 2012

Android beginner tutorial: Part 36 - Spinner selection management

In this tutorial we will learn how to handle user selection in Spinner widgets, as well as how to select items ourselves.

We'll make it so that when the user selects an item in the Spinner, a TextView, which is located under the Spinner, displays the selected item. We'll also add a button that, when clicked, will randomly choose and select one of the options in the Spinner.

Firstly, go to the Activity layout and add the necessary components:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/button_random"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/button_random" />
    
</LinearLayout>

Go to strings.xml and add a "button_random" item for the button's label:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Code For Food Test</string>
    <string name="menu_settings">Settings</string>
    <string name="button_random">Choose randomly</string>
    <string-array name="choices_array">
        <item>One</item>
        <item>Two</item>
        <item>Three</item>
        <item>Four</item>
        <item>Five</item>
        <item>Seven</item>
        <item>Eight</item>
        <item>Nine</item>
        <item>Ten</item>
    </string-array>

</resources>

In the MainActivity.java class, implement OnItemSelectedListener interface:

public class MainActivity extends Activity implements OnItemSelectedListener{

Declare a text variable. Also declare spinner, which is already used in the code, but we'll declare it as a private variable this time:

private TextView text;
private Spinner spinner;

Changes to make in the onCreate() function - apply value to text variable, declare a button variable, which references the "Choose randomly" button, add a listener for it, which sets the selection of the spinner randomly. Use the setSelection() method to do it. Use Math.round() and Math.random() to generate an index number. Use (int) in front of the number expression so that the setSelection() method comprehends it as an integer.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spinner = (Spinner)findViewById(R.id.spinner);
text = (TextView)findViewById(R.id.text);

String[] choices = getResources().getStringArray(R.array.choices_array);

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, choices);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(this);

Button button = (Button)findViewById(R.id.button_random);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
spinner.setSelection((int)Math.round(Math.random()*8));
}
});

}

Add two functions - onItemSelected and onNothingSelected. The first one is executed when an item is selected in the Spinner. The second is executed when nothing is selected. This happens rarely. It can happen, for example, if the data provider for the spinner is empty.

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    text.setText("The selected item is " + parent.getItemAtPosition(pos).toString());
    }
    
public void onNothingSelected(AdapterView<?> parent) {
    text.setText("Nothing is selected!");
    }

Full code:

package com.kircode.codeforfood_test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity implements OnItemSelectedListener{

private TextView text;
private Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spinner = (Spinner)findViewById(R.id.spinner);
text = (TextView)findViewById(R.id.text);

String[] choices = getResources().getStringArray(R.array.choices_array);

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, choices);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(this);

Button button = (Button)findViewById(R.id.button_random);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
spinner.setSelection((int)Math.round(Math.random()*8));
}
});

}

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    text.setText("The selected item is " + parent.getItemAtPosition(pos).toString());
    }
    
public void onNothingSelected(AdapterView<?> parent) {
    text.setText("Nothing is selected!");
    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

Thanks for reading!

No comments:

Post a Comment