Spinner In Android
Spinner in android is used to show the drop down list to the user and select the item from the drop down list.
In this chapter we will learn how to implement spinner in Android with a simple example in Android Studio.
Example:
- Create a new project as SpinnerExample.
- Design the activity_main.xml as follows.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="hss_24.spinnerexample.MainActivity"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:src="@drawable/simply" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Please select the item" android:textSize="20sp" /> <Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="10dp"> </Spinner> </LinearLayout>
- Code the main java file as follows.
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Spinner spinner; // Spinner dropdown items String[] android_names = {"Cupcake", "Donut", "Eclair", "Froyo", "Ginger Bread", "Honeycomb", "IceCream Sandwich", "Jelly Bean", "Kitkat", "Lollipop", "MarshMallow"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner = (Spinner) findViewById(R.id.spinner); // create and set adapter for spinner final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android_names); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // display toast when spinner item is selected Toast.makeText(getApplicationContext(), "Selected item is " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } }
- Run the app and enjoy the output.
Download the project here
Please like and share...



No comments:
Post a Comment