SPINNER EXAMPLE
Spinner Example
A Spinner in XML layout in Android Studio can be used to provide a drop-down menu of items that the user can select from. Here’s how to use it:
- Add the Spinner to your layout XML file.
- Set the layout_width and layout_height properties to control the size of the Spinner. You can set the layout_width to match_parent to make the Spinner fill the entire width of the parent layout, or set it to a specific value in pixels or dp to control the width. The layout_height property can be set to wrap_content to make the Spinner the same size as its items, or set to a specific value in pixels or dp to control the height.
- You can also set additional properties, such as prompt to specify a prompt text that is displayed when the Spinner is first shown, and entries to specify the items that are displayed in the Spinner.
Here’s an example of a Spinner in XML layout in Android Studio that fills the entire width of the parent layout and displays a prompt text “Please choose an item”:
<?xml version="1.0" encoding="utf-8"?> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:prompt="Please choose an item" />
Note: To set the items that are displayed in the Spinner, you can use an array resource in your res/values directory. For example:
<string-array name="items"> <item>Item 1</item> <item>Item 2</item> <item>Item 3</item> </string-array>
And in your layout XML file:
<?xml version="1.0" encoding="utf-8"?> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/items" />
To handle the selected item of the Spinner in your code, you can use the setOnItemSelectedListener() method on the Spinner object to set a listener that is called when the user selects an item. For example:
Spinner mySpinner = findViewById(R.id.my_spinner); mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { // do something with the selected item } @Override public void onNothingSelected(AdapterView parent) { // do something when nothing is selected } });
That’s all about example of spinner in android You can now run your app and see the Spinner displayed in the layout. The user can select an item from the Spinner, and you can handle the selected item in your code.