Spinners provide a quick way to select one value from a set.
In the default state, a spinner shows its currently selected value. Touching
the spinner displays a dropdown menu with all other available values, from
which the user can select a new one.
activity_main.xml
-----------------------
<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"
tools:context=".MainActivity"
android:orientation="vertical">
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner" />
</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"
tools:context=".MainActivity"
android:orientation="vertical">
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner" />
</LinearLayout>
text.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:textSize="25dp"
android:layout_height="match_parent">
</TextView
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:textSize="25dp"
android:layout_height="match_parent">
</TextView
MainActivity.Java
------------------------
package com.android.anil.spinner; 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.Toast; public class MainActivity extends AppCompatActivity { Spinner sp; String[] citys={"Hyderabad","Secundrabad","Chennai","Bengaluru","Mumbai","Kolkata","Delhi","Pune","Anantapur","Tadipatri"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sp=(Spinner)findViewById(R.id.spinner); ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(MainActivity.this,R.layout.text,citys); sp.setAdapter(arrayAdapter); sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "Selected City is : "+citys[position], Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }
Output is:
------------------------
No comments:
Post a Comment