Manually set width of spinner dropdown list in android
Question
Is it possible to set the width of a spinner dropdown list in code? I have a spinner populated with integers, and it does not look good with the list expanding to full width. Can I set the width to wrap the content somehow?
Spinner hSpinner = (Spinner) timerView.findViewById(R.id.timer_hour_spinner);
ArrayList<Integer> hList = new ArrayList<Integer>(21);
for (int i = 0; i <= 20; i++) { hList.add(i); }
ArrayAdapter hAdapter = new ArrayAdapter(RemindMe.this, android.R.layout.simple_spinner_item, hList);
hAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hSpinner.setAdapter(hAdapter);
Thanks!
Linus
Solution
You can change the width of anything in code by adjusting its LayoutParams
. The details of that varies by container (LinearLayout
vs. RelativeLayout
vs. ...).
However, I'm confused why you want to change the width "in code". Why not just set the width to be wrap_content
in the layout XML?
OTHER TIPS
Just use:
setDropDownWidth(desiredWidth);
It is straightforward to control the spinner dropdown appearance. Try this:
//Step 1. create the drop down list
static List<String> special_Spinner_Display_List = new ArrayList<String>();
// add your values to the list...(this is best done using a for loop)
special_Spinner_Display_List.add(item1);
special_Spinner_Display_List.add(item2); //etc., etc.
//Step 2. build the spinner
ArrayAdapter arrayAdapter_special = new ArrayAdapter(this,
R.layout.your_special_spinner, special_Spinner_Display_List);
arrayAdapter_special.setDropDownViewResource(R.layout.special_spinner_dropdown);
specialSpinner.setAdapter(arrayAdapter_special);
//Step 3. create an XML layout file called special_spinner_dropdown where you can
//style to your heart's content. Here's an example:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/SpinnerDropdown"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#D5ECED"
android:ellipsize="marquee"
android:singleLine="true"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@color/black" />
That's it. Lemme know how it works!
Set dropdown width in xml file of spinner using the tag
android:dropDownWidth="@dimen/desired_width"
Explaination :
mDropDownWidth = pa.getLayoutDimension(R.styleable.Spinner_dropDownWidth,
ViewGroup.LayoutParams.WRAP_CONTENT);
this field is used for dropdown width when spinner item is initialized in Spinner class
for programatically changing spinner dropdown width above api level 16, use
mSpinner.setDropDownWidth(size_in_pixel);