Android drop down Spinner Example
Android Spinner Example
Today we create an Android Spinner, a drop down spinner to select a value from a list. We use spinner when we have to select an item from a long list. Like when we have to select Country from a spinner drop down item.
Android Spinner Example |
To Create a Spinner we have to do some simple steps,
- Create a Spinner in your XML activity.
- Implement in your Java class.
- Array list to show a drop down list in spinner.
- Array Adapter to integrate list in Array List.
Xml activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Spinner_Activity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Android Spinner"
android:layout_margin="20dp"
android:textStyle="bold"
android:textSize="18sp"/>
<androidx.appcompat.widget.AppCompatSpinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"/>
</LinearLayout>
public class Spinner_Activity extends AppCompatActivity {
Spinner spinner;
ArrayList<String> spinner_list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_);
spinner = findViewById(R.id.spinner);
spinner_list.add("Harpreet");
spinner_list.add("Studio");
spinner_list.add("View");
spinner_list.add("like");
spinner_list.add("share"); //4th position
spinner_list.add("subscribe");
spinner_list.add("youtube");
spinner_list.add("facebook");
spinner_list.add("instagram");
ArrayAdapter adapter = new ArrayAdapter(Spinner_Activity.this,
android.R.layout.simple_list_item_1,spinner_list); // simple list item is default list
// with single text view, you can create your own list also
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// spinner.setSelection(4); //it's starts from 0 so it's 4th position is share
if(spinner_list.contains("like"))
{
spinner.setSelection(spinner_list.indexOf("like")); //if you have a string to set on spinner
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(Spinner_Activity.this, "Selected item is "+
spinner.getSelectedItem().toString() + " \nPosition is "+i, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
Subscribe to Harpreet studio on Youtube
Like Harpreet Studio on Facebook
Follow me on Instagram
Install our Android app from Google Play store
No comments