Android Spinner Dropdown Example/Tutorial

In this tutorial, we will work on the spinner.Spinner is used to select the data from a drop down menu.In this, we use dummy data to spinner for drop down menu

So, Let’s start:-

1.Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.Create a layout for MainActivity.java that will be our main screen.

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" 
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:text="Countries"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
    <Spinner
        android:id="@+id/selectcountry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"></Spinner>

</LinearLayout>

3. Now define MainActivity.java as follows

MainActivity.java

package com.coderzpassion.myspinnersample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    //spinner
    Spinner countryspinner;
    //list to be set to spinner
    ArrayList<String> countries=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        countryspinner=(Spinner)findViewById(R.id.selectcountry);
        //prepare dummy data for spinner
        prepareDummyData();
        //adapter for spinner
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,countries);
        //attach adapter to spinner
        countryspinner.setAdapter(adapter);

        //handle click of spinner item
        countryspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                // clicked item will be shown as spinner
                Toast.makeText(getApplicationContext(),""+parent.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
    });

    }

    public void prepareDummyData()
    {
        countries.add("India");
        countries.add("Russia");
        countries.add("USA");
        countries.add("UK");
        countries.add("Australia");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.myspinnersample" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output

Screenshot_2016-02-27-23-49-17

 

Android ViewPager as Image Slider Example/Tutorial

Working with ViewPager to show image Slider. Following are required:-

  1. 1  Activity class containing viewpager.
    2  Adapter class to be set to viewpager.
    3  Fragment class whose view will be displayed in viewpager

//MainActivity containing viewpager

MainActivity.java

package com.androidruler.imageslider;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ViewPager pager;
    List<Fragment> fragments;
    // list containing id's of images we want to show in viewpager 
    // images are in drawable folder
    ArrayList<Integer> images=new ArrayList<Integer>(){{
        add(R.drawable.wonder1);
        add(R.drawable.wonder2);
        add(R.drawable.wonder3);
        add(R.drawable.wonder4);
        add(R.drawable.wonder5);
        add(R.drawable.wonder6);
        add(R.drawable.wonder7);
    }};
    PagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         pager = (ViewPager) findViewById(R.id.viewPager);
        
        //method to create the required fragments to show in viewpager and return as a fragment list
        fragments=getFragments();
        adapter=new PagerAdapter(getSupportFragmentManager(),fragments);
        pager.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
      //  getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

// Adapter class which is set to viewpager

PagerAdapter.java

   class PagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;
        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
       public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }
    }

    
    //method to get list of fragments to be displayed in viewpager 
    private List<Fragment> getFragments() {
        List<Fragment> fList = new ArrayList<Fragment>();
        for (int i = 0; i < images.size(); i++) {
            fList.add(MyImageSlider.newInstance(images.get(i)));
        }
        return fList;
    }
}

//Fragment class

MyImageSlider.java

package com.androidruler.imageslider;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

// its the fragment from where we create fragments
public class MyImageSlider extends Fragment {

    int imageid;

// static method to create the MyImageSlider Fragment containing image
    public  static MyImageSlider newInstance(int id)
    {
        MyImageSlider slider=new MyImageSlider();
        Bundle b=new Bundle();
        b.putInt("imageid", id);
        slider.setArguments(b);
        return slider;
    }


// get the image id from fragment in this method although we can also get in onCreateView.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageid=getArguments().getInt("imageid");
    }


// this method returns the view containing the required which is set while creating instance of fragment
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.adapterview, container, false);
        ImageView iv=(ImageView)view.findViewById(R.id.myimage);

        iv.setImageResource(imageid);

        return view;
    }
}

//layout for MainActivity.java

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">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

//layout for MyImageSlider

adapterview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/myimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Output

Screenshot_2016-02-27-18-14-28