In this tutorial we will learn how to use Spinner.
Android spinner is like the drop down hidangan with multiple values from which the end user can select only one value.Android spinner is associated with AdapterView. So you need to use one of the adapter classes with spinner.
We will select item from spinner and set it to the TextView
Step 1: Create a new project OR Open your project
Step 2: Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:padding="5dp"tools:context=".MainActivity"><Spinnerandroid:id="@+id/spinner"android:layout_width="match_parent"android:layout_height="wrap_content"></Spinner><TextViewandroid:id="@+id/outputSpinnerTv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"android:textSize="30sp"android:textColor="#000"android:layout_centerVertical="true"android:layout_centerHorizontal="true"/></RelativeLayout>
MainActivity.java
package com.blogspot.atifsoftwares.spinnerexample;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.TextView;public class MainActivity extends AppCompatActivity {Spinner mSpinner;TextView mOutputSpinnerTv;//options to be displayed in spinnerString[] mOptions = {"Canada" , "Pakistan" , "Turkey" , "US"};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mSpinner = findViewById(R.id.spinner);mOutputSpinnerTv = findViewById(R.id.outputSpinnerTv);//Creating the ArrayAdapter instance having the list of optionsArrayAdapter aa = new ArrayAdapter(this , android.R.layout.simple_spinner_item , mOptions);aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//setting the ArrayAdapter data on the SpinnermSpinner.setAdapter(aa);//spinner item click handlermSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent , View view , int position , long id) {//METHOD 1: Get text from selected item's position & set it to TextView//mOutputSpinnerTv.setText(parent.getItemAtPosition(position).toString());//METHOD 2: Get the position of item selected , & perform specific taskif (position==0){mOutputSpinnerTv.setText("Canada is selected...");}if (position==1){mOutputSpinnerTv.setText("Pakistan is selected...");}if (position==2){mOutputSpinnerTv.setText("Turkey is selected...");}if (position==3){mOutputSpinnerTv.setText("US is selected...");}}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}});}}
0 Response to "Spinner Example - Android"