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

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.

ArrayAdapterLet 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(savedInstanceState); …

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. This drawab…

DatePickers in Android

DatePicker is a view which lets the user select a date showing a calendar or 3 spinners for dd, mm and yy.

Let us see how to use this.
Easy Method: To use a DatePicker you can use DatePickerDialog. This can be created and shown programmatically too.

publicvoidonCreate(Bundle b){/*********/ Button btn =(Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener(){@OverridepublicvoidonClick(View v){ showPickerDialog();}});}privatevoidshowPickerDialog(){ DatePickerDialog dtPickerDlg =new DatePickerDialog(this,this, 2017,10,20); dtPickerDialog.show();}

In our xml file, let us have a button and in the onclick listener of the button, let us display the date picker dialog - we call showPickerDialog.

In showPickerDialog,  we are using a random date to initialize.

The first  parameter is the context. Second parameter is the class which implements the interface OnDateSetListener. Next three parameters are year, month (Jan is 0) and …