Android Spinner

Android Spinner is a view that works similarly to a dropdown list in that it allows you to choose one option from a list of options. When we click on it, it shows a dropdown list of all values and allows us to easily select one item from the list of items. The presently selected value will be the default value of the android spinner, and we can easily tie items to the spinner objects using Adapter. In general, we use an ArrayAdapter in our Java file to populate our Spinner control with a list of elements.

Generally, in android we have a different types of adapters available to fetch the data from different data sources to fill the data into adapter views, those are

AdapterDescription
ArrayAdapterIt will expect an Array or List as input.
CurosrAdapterIt will accepts an instance of a cursor as an input.
SimpleAdapterIt will accept a static data defined in the resources.
BaseAdapterIt is a generic implementation for all three adapter types and it can be used for ListView, Gridview or Spinners based on our requirements

Different Attributes for Spinner Widget

XML attributesDescription
android:idUsed to specify the id of the view.
android:textAlignmentUsed to the text alignment in the dropdown list.
android:backgroundUsed to set the background of the view.
android:paddingUsed to set the padding of the view.
android:visibilityUsed to set the visibility of the view.
android:gravityUsed to specify the gravity of the view like center, top, bottom, etc

Example to demonstrate the Spinner

Creating the activities: There will be one activity and hence one XML file for MainActivity. activity_main.xml: XML file for first activity consists of constraint layout with spinner widget. Below is the code for the XML file for activity:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#D5DCA5A5"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="18dp"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="18dp"
        android:layout_marginRight="18dp"
        android:background="#FFFFFF"
        android:dropDownWidth="match_parent"
        android:spinnerMode="dropdown"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="20dp"
        android:adjustViewBounds="false"
        android:background="#B4716E6C"
        android:scaleType="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinner"
        app:srcCompat="@drawable/tomandjerry" />

    <Button
        android:id="@+id/redo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Redo"
        app:backgroundTint="#877F7C"
        app:layout_constraintBottom_toTopOf="@+id/spinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/undo"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/undo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Undo"
        app:backgroundTint="#877F7C"
        app:layout_constraintBottom_toTopOf="@+id/spinner"
        app:layout_constraintEnd_toStartOf="@+id/redo"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Creating the Java file: There is one activity and hence one Java file for the MainActivity file. Java file for Main Activity, in which Array Adapter is used to bind data to the spinner. We will fill data in the array of strings and bind that data to the spinner. Here is the code:  

MainActivity.java

package in.codingtimes.spinnerscale;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;


import java.util.ArrayList;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ArrayList<String> mylist;
    ImageView imageView;
    Integer currentIndex = 0;
    Spinner spinner;
    String[] scaletype;
    Boolean eventTriggered = true;

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

        Button undo = findViewById(R.id.undo);
        Button redo = findViewById(R.id.redo);

        undo.setOnClickListener(this);
        redo.setOnClickListener(this);

        spinner = findViewById(R.id.spinner);

        scaletype = getResources().getStringArray(R.array.scaletype);

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, scaletype);
        spinner.setAdapter(arrayAdapter);

        imageView = findViewById(R.id.imageView);

        mylist = new ArrayList<String>();


        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if(eventTriggered.equals(true)){
                    if (mylist.size() >= 5) {
                        mylist.remove(0);
                    }
                    mylist.add(spinner.getSelectedItem().toString());
                }

                setScaleType(spinner.getSelectedItem().toString());

                if(eventTriggered.equals(false)) eventTriggered = true;
            }

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

            }
        });

    }

    public void setScaleType(String scaleType){
        switch(scaleType){
            case "CENTER":
                imageView.setScaleType(ImageView.ScaleType.CENTER);
                break;
            case "CENTER_CROP":
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                break;
            case "CENTER_INSIDE":
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                break;
            case "FIT_CENTER":
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                break;
            case "FIT_START":
                imageView.setScaleType(ImageView.ScaleType.FIT_START);
                break;
            case "FIT_END":
                imageView.setScaleType(ImageView.ScaleType.FIT_END);
                break;
            case "FIT_XY":
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                break;
            case "MATRIX":
                imageView.setScaleType(ImageView.ScaleType.MATRIX);
                break;
        }
    }

    @Override
    public void onClick(View v) {

        if(mylist.isEmpty()){
            return;
        }

        currentIndex= mylist.indexOf(imageView.getScaleType().name());

        switch(v.getId()){
            case R.id.undo:
                if(currentIndex > 0)
                    currentIndex--;
                break;
            case R.id.redo:
                if(currentIndex < mylist.size()-1)
                    currentIndex++;
                break;
        }
        eventTriggered = false;
        spinner.setSelection(Arrays.asList(scaletype).indexOf(mylist.get(currentIndex)));


    }
}

strings.xml

<resources>
    <string name="app_name">SpinnerScale</string>
    <string-array name="scaletype">
        <item>CENTER</item>
        <item>CENTER_CROP</item>
        <item>CENTER_INSIDE</item>
        <item>FIT_CENTER</item>
        <item>FIT_START</item>
        <item>FIT_END</item>
        <item>FIT_XY</item>
        <item>MATRIX</item>
    </string-array>
</resources>

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Android Progress Bar

Source Code – https://github.com/Adityaraj-30/SpinnerScale_Android.git


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , SwiggyKFC


One comment

Leave a Reply

Your email address will not be published.