Lets Take a spin on Custom Spinner in Android
In this topic of “How to Create Android Widgets” we will learn how to create a custom spinner in android. Spinners is one of the widgets in Android which allows the user to pick one item from a list of items. The items in the Spinner come from the Adapter associated.
If you are not clear with the basic concepts of Android, you can pursue this Android online training to understand each & every nuance of the technology.
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 drop-down menu with all other available values, from which the user can select a new one.
Example : Displaying the list of days of the week and on selecting an item it will display that item in a Toast.
1) Declare the spinner Globally i.e outside the onCreate method
// Declare the variable outside onCreate Spinner spin;
2) Within the onCreate method :
- Typecasting spinner
- Creating Data Pump
- Declaring an ArrayAdapter
// Typecasting the variable here spin = (Spinner) findViewById(R.id.spn1); // Array of Months acting as a data pump String[] objects = { "January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November","December" }; // Declaring an Adapter and initializing it to the data pump ArrayAdapter adapter = new ArrayAdapter( getApplicationContext(),android.R.layout.simple_list_item_1 ,objects); // Setting Adapter to the Spinner spin.setAdapter(adapter); // Setting OnItemClickListener to the Spinner spin.setOnItemSelectedListener(this);
3) Outside the onCreate method : The callback methods that are necessary to be implemented with OnItemSelectedListener.
There are two callback methods :
- onItemSelected
- onNothingSelected
// Defining the Callback methods here public void onItemSelected(AdapterView parent, View view, int pos, long id) { Toast.makeText(getApplicationContext(), spin.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG) .show(); } // Defining the Callback methods here @Override public void onNothingSelected(AdapterView arg0) { // TODO Auto-generated method stub }
Now you know how to implement Spinner , which is a widget in Android. Develop the skills you need to create successful mobile apps in a Flutter Certification Training that covers all the fundamentals.
Now we will Create a Custom Spinner in Android:
So why wait, Lets see how to Implement a Custom Spinner that will display an image followed by some text as elements of the Spinner.
Take a look on what we are tending to create :
This is more like a “real and practical” Spinner.
Steps to Create a Custom Spinner:
1) Before onCreate method :
- Declare an Array of the items that has to be displayed in the Spinner
- Declare an Array with the resource id’s of the corresponding images that has to be displayed with the items.
// Declaring the String Array with the Text Data for the Spinners String[] Languages = { "Select a Language", "C# Language", "HTML Language", "XML Language", "PHP Language" }; // Declaring the Integer Array with resourse Id's of Images for the Spinners Integer[] images = { 0, R.drawable.image_1, R.drawable.image_2, R.drawable.image_3, R.drawable.image_4 };
2) Inside onCreate method :
- Typecasting spinner
- Creating Data Pump
- Declaring and assigning a Custom Adapter
// Declaring and typecasting a Spinner Spinner mySpinner = (Spinner) findViewById(R.id.spinner1); // Setting a Custom Adapter to the Spinner mySpinner.setAdapter(new MyAdapter(MainActivity.this, R.layout.custom, Languages));
3) After onCreate method:
- Defining Custom Adapter i.e MyAdapter
// Creating an Adapter Class public class MyAdapter extends ArrayAdapter { public MyAdapter(Context context, int textViewResourceId, String[] objects) { super(context, textViewResourceId, objects); } public View getCustomView(int position, View convertView, ViewGroup parent) { // Inflating the layout for the custom Spinner LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom, parent, false); // Declaring and Typecasting the textview in the inflated layout TextView tvLanguage = (TextView) layout .findViewById(R.id.tvLanguage); // Setting the text using the array tvLanguage.setText(Languages[position]); // Setting the color of the text tvLanguage.setTextColor(Color.rgb(75, 180, 225)); // Declaring and Typecasting the imageView in the inflated layout ImageView img = (ImageView) layout.findViewById(R.id.imgLanguage); // Setting an image using the id's in the array img.setImageResource(images[position]); // Setting Special atrributes for 1st element if (position == 0) { // Removing the image view img.setVisibility(View.GONE); // Setting the size of the text tvLanguage.setTextSize(20f); // Setting the text Color tvLanguage.setTextColor(Color.BLACK); } return layout; } // It gets a View that displays in the drop down popup the data at the specified position @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } // It gets a View that displays the data at the specified position @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } }
4) Create a XML file named as activity_mail.xml
- It includes a Spinner
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Spinner android:drawSelectorOnTop="true" android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:prompt="@string/select"> </LinearLayout>
5) Create a XML file named as custom.xml :
It includes
- One Image View
- One Text View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="3dip"> <ImageView android:id="@+id/imgLanguage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"> </ImageView> <TextView android:id="@+id/tvLanguage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="8dp" android:text="Text Here"> </TextView> </LinearLayout>
[buttonleads form_title=”Download Code” redirect_url=https://edureka.wistia.com/medias/sl63rjlcfc/download?media_file_id=64011904 course_id=318 button_text=”Download Code”]
Have a doubt in the discussed concepts? Please mention it in the comments section and we will get back to you.
Stay tuned for more tutorials to learn how to create Android widgets!
How to create Android Widgets:Custom Toast
Great blog!
Thanks, Divya! We’re glad you found the blog useful. We thought you might find these blogs useful: https://www.edureka.co/blog/android-tutorial-custom-toast/
https://www.edureka.co/blog/tag/how-to-create-android-widgets/
You can also subscribe to our blog to stay posted on upcoming Android blogs.
can we set the height of the spinner dropdown to a default value?
Hi Rishi, thanks for checking out our blog. We can use android:layout_height=”60dp” android:paddingLeft=”20dp” in the xml. and ArrayAdapter adapter = new ArrayAdapter(this,R.layout.custom_dropdown_list, items);
dropdown.setAdapter(adapter); in the java file to do this. Hope this helps. Cheers!
Is there a way to display an image, instead of text after selecting an item from spinner dropdown menu?
Hey Sana, thanks for checking out the blog. To answer your query, yes we can display an image, instead of text after selecting an item from spinner dropdown menu. This can be done using an imageview. With the options selected from the spinner we can change the image accordingly. Hope this helps.
You have used this call:
mySpinner.setAdapter(new MyAdapter(MainActivity.this, R.layout.custom,
Languages));
for this constructor:
public MyAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
}
You are wrongly passing the Row layout to the TextView id. Please correct the arguments or the constructor.
Hey Harsh Vardhan, thanks for checking out our blog. Every resource you create (or which is provided by Android) is referenced by an integer in R, called a resource id. So we are passing the id of the custom xml to the Myadapter constructor. There is nothing wrong in it. Cheers!
how to use it in fragments?
Hi Mohsen, we can do this by defining an Adapter and calling getActivity() method.
Refer the below piece of code for your reference.
ArrayAdapter myAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_spinner_item, locations);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(myAdapter);
Note : Make sure your Fragment successfully attached to your activity so that getActivity() not NULL.
Hope this helps.
Nice tutorial
Thank you…a well explained example!!
Spot on with this write-up, I truly feel this website requirements a lot more consideration. I’ll almost certainly be once again to read far more, thanks for that information.
I’m impressed, I need to say. Definitely rarely do I encounter a weblog that is both educative and entertaining, and let me tell you, you’ve got hit the nail on the head. Your concept is outstanding; the concern is something that not sufficient folks are speaking intelligently about. I am pretty pleased that I stumbled across this in my search for something relating to this.
I’d need to check with you here. Which just isn’t some thing I generally do! I get pleasure from reading a post that can make consumers think. Also, thanks for permitting me to comment!