By default the spinner width is set to fit the largest item in the dropdown but I want it to be the same width as the selected item.
<android.widget.Spinner
android:id="@+id/tab_spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:entries="@array/countries" />
As you can see in the right side image, the spinner is way too long, because of the long item in the list.
How can I resize it to the selected item width ?
Setting the spinners XML to:
worked for me.
By default,
Spinner
will try to measure some of your dropdown views and use the max width found. This happens inSpinner#measureContentWidth()
, aprotected
method ofSpinner
called inSpinner#onMeasure()
.One way to solve the issue is to make sure your
SpinnerAdapter#getView()
method always usesSpinner#getSelectedItemPosition()
for itsposition
argument.I can think of two possible solutions:
1. Creating a custom spinner with a wrapper adapter
Make sure to use this in your
xml
layout, instead of a normal<Spinner>
.Be careful that
DynamicWidthSpinner#getAdapter()
will return aWrapperSpinnerAdapter
; use itsgetBaseAdapter()
method to access to your adapter.2. Adapting your custom adapter
Be careful that
parent
ingetView()
might not always be aSpinner
.Do this is on item selected