Thursday, 22 January 2015

Spinner Example

Spinner Example in Android.








String.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Spinner Example</string>
    <string name="action_settings">Settings</string>
    <string-array name="fruits">
        <item >apple</item>
        <item >mango</item>
        <item >sugarcane</item>   
        <item >cherry</item>         
    </string-array>

</resources>

activity_main.xml:

<RelativeLayout 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" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="46dp" />

</RelativeLayout>

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="@android:color/black"
    android:textSize="25sp"  >
   
</TextView>

MainActivity.java:

package com.swamys.spinnerexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemSelectedListener{
       Spinner spinner;
       String[] fruits={"apple","mango","sugarcane","cherry"};

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              Spinner spinner=(Spinner)findViewById(R.id.spinner1);
              ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, fruits);
              spinner.setAdapter(adapter);
              spinner.setOnItemSelectedListener(this);
             
                     }
      
      
       public void onItemSelected(AdapterView<?> arg0, View view, int poistion,
                     long arg3) { 
              Toast.makeText(getApplicationContext(), ""+fruits[poistion],Toast.LENGTH_LONG).show();
              
       }
       @Override
       public void onNothingSelected(AdapterView<?> arg0) {
                           
       }
}

No comments:

Post a Comment