Friday, June 16, 2017

Android Spinner and it's adapter

Welcome to this post. In this post, we going to learn about Spinner.

Spinner is really awesome to give user choice to select from a small list. you can use the spinner to get a value from a list.

In this project, we are going to create a list that shows a list in the spinner.
The list has 3 items-

  • Everyday
  • Today
  • Schedule


Let's start- layout name as you want.

I create a fragment that contains a spinner and a text view. I am currently using the same spinner in two or more file so I use the fragment. But you can use on your desired layout.

Note: I use Java and Kotlin code simultaneously. First is java and the second one is Kotlin.

Let's add XML Code-
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:padding="10dp"
        android:text="@string/select_task_type"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:padding="10dp"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"/>

</android.support.constraint.ConstraintLayout>
Now you can use this layout in any other layout. Now time to write java code-
private Spinner spinner;
assign view
spinner = (Spinner) findViewById(R.id.spinner);

In kotlin, we need to add only one line.
val spinner: Spinner = findViewById(R.id.spinner)

Now create a list
 // Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add(MainActivity.EVERYDAY);
categories.add(MainActivity.TODAY);
categories.add(MainActivity.SCHEDULE);
Kotlin:
val categories = ArrayList<String>()
categories.add("EVERYDAY")
categories.add("TODAY")
categories.add("SCHEDULE")
Now create an adapter for this spinner-
 // Creating adapter for spinner
ArrayAdapter dataAdapter = new ArrayAdapter<>
     (this, android.R.layout.simple_spinner_item, categories);
Kotlin:
val dataAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, categories)
Now add a drop-down layout style with list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Kotlin:
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
set data adapter to spinner
spinner.setAdapter(dataAdapter);
Kotlin:
spinner.adapter = dataAdapter

I add a method to get selected data from the list- In my case method name is getTaskType.
we have to do-
1. we need to add setOnItemSelectedListener to our spinner
2. so we also override two methods name
i) onItemSelected -> when we select something then this method is called
ii) onNothingSelected -> if the user is not select anything

Let's see the code-
//get task type from spinner
private String getTaskType() {

      final String[] tasks = new String[]{null};

      // Spinner click listener
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, 
                    int position, long id) {
              tasks[0] = parent.getItemAtPosition(position).toString();
            }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {
              //do nothing
          }
      });

     return tasks[0];
}

Kotlin:
private fun getTaskType(spinner:Spinner):String {

        var tasks = "no text"

        // Spinner click listener
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                tasks = parent.getItemAtPosition(position).toString()
            }
            
            override fun onNothingSelected(parent: AdapterView<*>) {
                //do nothing
            }
        }
        
        return tasks
    }

That's it.
this post will help you in both case, if you are working with java or kotlin.
Now you can use the spinner in your project.
Happy coding.

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :