Wednesday, December 26, 2012

46 How to create custom Spinner Control in Android

From Developer.android.com: “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.”
Android Custom Spinner Control - Figure 1

In this tutorial, we show you how to customize a spinner with image, text

This project is developed in Eclipse 4.2.0.

1. First make xml main layout for app


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Get spinner content"
        android:layout_marginBottom="15dp"
         android:onClick="button_click"/>
   
       <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="15dp"
        android:prompt="@string/prompt"/>
      
       <TextView android:id="@+id/textView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:textSize="27px"
         android:text="Show spinner choice"
         android:gravity="center"
         android:textColor="#CD2134" 
         android:textStyle="bold"  />
</LinearLayout>
The layout have a button, a spinner and a textview. We’ll custom spinner and when click on the button, the text view will show the content of spinner . All codes show below

package com.example.spinnerwidget;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class SpinnerActivity extends Activity {
       // declare three arrays for content of spinner
       String[] strings = {"Inter Milan","AC Milan",
                   "Manchester City", "Barcelona", "Valencia","Juventus"};
        
       String[] subs = {"Italia","Italia",
                   "England", "Spain", "Spain","Italia"};
        
       int arr_images[] = { R.drawable.pic1,
                            R.drawable.pic2, R.drawable.pic3,
                            R.drawable.pic4, R.drawable.pic5, R.drawable.pic6};
          
              Button button;
              TextView textview
              Spinner spinner;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        button = (Button)findViewById(R.id.button1);
        textview = (TextView)findViewById(R.id.textView);
        spinner = (Spinner)findViewById(R.id.spinner1);
        spinner.setAdapter(new MyAdapter(this, R.layout.row, strings));
    }
    // button onclick
    public void button_click(View view) {
              textview.setText(spinner.getSelectedItem().toString());
       }
    // Adapter class for spinner control
    public class MyAdapter extends ArrayAdapter<String>{
        
        public MyAdapter(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }

        @Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.row, parent, false);
            TextView label=(TextView)row.findViewById(R.id.company);
            label.setText(strings[position]);

            TextView sub=(TextView)row.findViewById(R.id.sub);
            sub.setText(subs[position]);

            ImageView icon=(ImageView)row.findViewById(R.id.image);
            icon.setImageResource(arr_images[position]);
            return row;
            }
        }
}

Now the layout for each row in the spinner.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
> 
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/pic1"/>
    <TextView
         android:layout_toRightOf="@+id/image"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:text="Inter Milan"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="1dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:text="Italia"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>

And make some change in strings.xml.

<resources>
    <string name="app_name">spinnerWidget</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_spinner">SpinnerActivity</string>
    <string name="prompt">  Select one Football Club  </string>
    <drawable name="red">#C11B17</drawable>
    <drawable name="darkgrey">#606060</drawable>
</resources>

2. DEMO
2.1. When click on the spinner

Android Custom Spinner Control - Figure 2


2.2. When click on the button

Android Custom Spinner Control - Figure 3


You can download all source codes from here
Reference: http://www.coderzheaven.com/2011/07/18/customizing-a-spinner-in-android/

46 comments:

  1. Very nice tutorial…But i want to create rounded corners in my spinner item but it is not showing. I was trying code from this link.
    http://www.bounty4u.com/custom-spinner/

    ReplyDelete
  2. Hi! Thank you very much. really very helpful tutorial.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Nice post, I bookmark your blog because I found very good information on your blog, Thanks for sharing more information .
    Android App development Manchester & Iphone App Development manchester

    ReplyDelete
  5. how to set height of the overall spinner dropdown list?

    ReplyDelete
  6. i need a spinner if click to spinner so it will open below to set text, i already tried some code it will success in marshmallow, if any possibility for kitkat version???

    ReplyDelete
  7. more impressive and informative article, thanks for your valuable information and time. keep rocks.
    Android Training in chennai|Home

    ReplyDelete
  8. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    Best Hadoop training in chennai

    ReplyDelete
  9. I simply wanted to thank you so much again. I am not sure the things that I might have gone through without the type of hints revealed by you regarding that situation.
    Click here:
    angularjs training in annanagar
    Click here:
    angularjs training in bangalore
    Click here:
    angularjs training in chennai
    Click here:
    angularjs training in velarchery
    Click here:
    angularjs training in sholinganallur

    ReplyDelete
  10. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Blueprism training in Chennai

    Blueprism training in Bangalore

    Blueprism training in Pune

    Blueprism online training

    Blueprism training in tambaram

    ReplyDelete
  11. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    ReplyDelete
  12. You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content

    Java training in Bangalore | Java training in Electronic city

    Java training in Bangalore | Java training in Marathahalli

    Java training in Bangalore | Java training in Btm layout

    Java training in Bangalore | Java training in Jaya nagar

    ReplyDelete
  13. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me
    Data Science Training in Chennai | Data Science Training institute in Chennai
    Data Science course in anna nagar
    Data Science course in chennai | Data Science Training institute in Chennai | Best Data Science Training in Chennai
    Data science course in Bangalore | Data Science Training institute in Bangalore | Best Data Science Training in Bangalore
    Data Science course in marathahalli | Data Science training in Bangalore

    ReplyDelete
  14. I know you feel more happy when you get things done and best of all those things are your most precious treasure.
    online Python training
    python training in chennai

    ReplyDelete
  15. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.

    rpa training in chennai
    rpa training in bangalore
    rpa course in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  16. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    python training in chennai
    python training in chennai
    python training in bangalore

    ReplyDelete

  17. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.
    AWS Training in Pune | Best Amazon Web Services Training in Pune


    Amazon Web Services Training in OMR , Chennai | Best AWS Training in OMR,Chennai


    AWS Training in Chennai |Best Amazon Web Services Training in Chennai

    ReplyDelete
  18. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    informatica mdm online training

    apache spark online training

    angularjs online training

    devops online training

    aws online training

    ReplyDelete
  19. Hey Nice Blog!! Thanks For Sharing!!! Wonderful blog & good post. It is really very helpful to me, waiting for a more new post. Keep Blogging ! Here is the best angularjs online training with free Bundle videos .

    contact No :- 9885022027.
    SVR Technologies

    ReplyDelete
  20. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts, digital marketing training in bangalore

    ReplyDelete
  21. thank you so much for this nice information Article, Digitahanks for sharing your post with us.citrix training in bangalore

    ReplyDelete
  22. I am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing. Great efforts.

    Upgrade your career Learn Oracle Training from industry experts gets complete hands on Training, Interview preparation, and Job Assistance at My Training Bangalore.

    ReplyDelete
  23. Effective blog with a lot of information. I just Shared you the link below for ACTE .They really provide good level of training and Placement,I just Had Android Classes in ACTE , Just Check This Link You can get it more information about the Android course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  24. Title:
    Top Oracle PLSQL Training Institute in Chennai | Infycle Technologies

    Description:
    Learn Oracle PLSQL for making your career towards a sky-high with Infycle Technologies. Infycle Technologies is the top Oracle PLSQL Training Institute in Chennai, offering programs in Oracle such as Oracle PL/SQL, Oracle DBA, etc., in the 200% hands-on practical training with professional specialists in the field. In addition to that, the interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 100% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.
    Best training for Chennai

    ReplyDelete
  25. Best training in ChennaiData Science Training Institute in Chennai | InfycleTechnologies

    Don’t miss this Infycle Education feast!! Special menu like updated Java, Python, Big Data, Oracle, AWS, and more than 20 software-related courses. Just get Data Science from the best Data Science Training Institute in Chennai, Infycle Technologies, which helps to recreate your life. It can help to change your boring job into a pep-up energetic job because, in this feast, you can top-up your knowledge. To enjoy this Data Science training in Chennai, just make a call to 7502633633.

    ReplyDelete
  26. Dream your career towards Big Data? Then come to Infycle Technologies, the best software training center in Chennai, which gives the combined and best Big Data Hadoop Training in Chennai, in a 100% hands-on training guided by professional teachers in the field. In addition to this, the interviews for the placement will be guided to the candidates, so that, they can face the interviews without struggles. Apart from all, the candidates will be placed in the top MNC's with a bet salary package. Call 7502633633 and make this happen for your happy life.
    Best software training in chennai

    ReplyDelete
  27. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Selenium course in Chennai for tech professionals, freshers, and students at the best offers. In addition to the Selenium, other in-demand courses such as Python, Big Data, Oracle, Java, Python, Power BI, Digital Marketing, Cyber Security also will be trained with hands-on practical classes. After the completion of training, the trainees will be sent for placement interviews in the top companies. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  28. I appreciate you providing this useful post...
    Aws training in hyderabad

    ReplyDelete