Skip to main content

Using spinners in android

Spinner in android is a view which shows you a drop down menu and lets you select one of the items.

Let us see how to use a spinner in your android program.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.hegdeapps.myapplication.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="select currency" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="150dp"
        android:layout_height="40dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
         />
</LinearLayout>

Next you need to specify what elements should the drop down menu should display. For that you can use an adapter like the one used for listview.

protected void onCreate(Bundle savedInstanceState) {
        /********other code******/
        Spinner sp =(Spinner) findViewById(R.id.spinner);
        final String arr[] = new String[]{"Rupee","US Dollar","Euro"};/*values for drop down*/
        ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,arr);
        sp.setAdapter( adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(view,"You selected "+arr[position],Snackbar.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

What happens when we select one of the items of the spinner? To specify that, you need to use onItemSelectedListener as shown above.


Let us look at another example. First we will see the layout file with spinner in it.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.hegdeapps.myapplication.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Length of square:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/len"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Select:"
            android:textSize="18sp" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="0dp"
            android:layout_weight="1"
            android:entries="@array/type" />

    </LinearLayout>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="Calculate" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Answer is"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/ans"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text=" "
            android:textSize="18sp" />
    </LinearLayout>
</LinearLayout>

In this example, we are using a spinner to select length, perimeter or area of a square. But we will not use an adapter. Instead we specify the values in xml as

android:entries = "@array/type"

where this type is a string array specified in an xml file in values folder, say strings.xml


<resources>
    <string name="app_name">My Application</string>
    <string name="action_settings">Settings</string>
    <string-array name="type">
        <item>length</item>
        <item>perimeter</item>
        <item>area</item>
    </string-array>
</resources>

So this string array type is used for populating the spinner instead of using java code.

Spinner has a method getItemSelected(), which we shall use. Please remember that the method returns an object, so we have to type cast it.


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        Spinner sp =(Spinner) findViewById(R.id.spinner);
        EditText etLen = (EditText) findViewById(R.id.len);
        Button btnCalculate = (Button)findViewById(R.id.button);
        btnCalculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculate();
            }
        });

    }

    private void calculate() {
        Spinner sp =(Spinner) findViewById(R.id.spinner);
        EditText etLen = (EditText) findViewById(R.id.len);
        String str = (String)sp.getSelectedItem();
        String stLen = etLen.getText().toString();
        int len = Integer.valueOf(stLen);
        int ans=len;
        if(str.equals("length")){
            ans = len;
        }else if(str.equals("perimeter")){
            ans = 4*len;
        } else if(str.equals("area")){
            ans = len*len;
        }
        TextView tvAns = (TextView) findViewById(R.id.ans);
        tvAns.setText(String.valueOf(ans));
    }
}

As we can see, we are using the getSelectedItem() to extract value from spinner and using it in calculation. Also not that we are not using any kind of adapter for the spinner.

Here is the output of the program.


You can also specify whether the spinner shows values as a dropdown or a dialog using this xml attribute

  android:spinnerMode =dialog

 android:spinnerMode =dropdown

Comments

Popular posts from this blog

Drawables in Android - Layer drawable

Let us see how to use layer drawable. You can have two or more bitmaps on different layers to create such a drawable Using xml : You should use layer-list in your xml file to create layerdrawable. Here is layer.xml <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/whiteicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/blueicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/redicon" android:gravity="top|left"/> </item> </layer-list> We are using three different bitmaps whiteicon.png, redicon.png and blueicon.png which are present in /res/drawable/mdpi folder. All these are of different sizes and aligned to top left. Thi

Copy to clipboard

In my upcoming app, I have codes which I display. These are some times lengthy, and I want the app to be able to copy this to clipboard. Once it is in clipboard, users can paste it anywhere. So how do you copy some text from your app to clipboard. You need to use clipboard manager. Clipboard Manager This class sets and gets data for the clipboard using Clipdata objects.  You can get the object of this class using system service.  - using statement context.getSystemService(Context.CLIPBOARD_SERVICE) Example I have a dummy project with a button, onclick of which copies content to clipboard. Here is my activity file package com . hegdeapps . testapp ; import android.content.ClipData ; import android.content.ClipboardManager ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.TextView ; public class MainActivity extends AppCompa

Simple ListView Adapter and list item select

When you are using a listview in your applications many a times you will write your own adapter to display item. But if your list is very simple showing a list of strings, you can use inbuilt adapters like ArrayAdapter, SimpleCursorAdapter etc. ArrayAdapter Let us look at an example <?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" > <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="match_parent" android:layout_margin="20dp"> </ListView> </LinearLayout> And add these lines to the onCreate method of the activity. super.onCreate(savedInstanc