Manually set the spinner dropdown width in android

Is it possible to set the width of the spinner drop-down list in the code? I have a counter filled with integers and it doesn't look good when the list expands to full width. Can I set the width to somehow wrap the content?

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

+3
source share
4 answers

You can change the width of the code in the code by adjusting it LayoutParams. The details of this depend on the container ( LinearLayoutvs. RelativeLayoutvs ....).

However, I am confused why you want to change the width "in code". Why not just set the width wrap_contentin the XML layout?

+1

:

setDropDownWidth(desiredWidth);
+2

. :

//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 content.  Here 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" />

. Lemme , !

0
source

Set the width of the drop-down list in the xml file of the counter using the tag

Android: dropDownWidth = "@ DIMEN / desired_width"

Explanation:

mDropDownWidth = pa.getLayoutDimension(R.styleable.Spinner_dropDownWidth,
        ViewGroup.LayoutParams.WRAP_CONTENT);

this field is used for the width of the drop-down list when initializing the counter element in the Spinner class

for programmatically changing counter cutting width above api level 16, use

mSpinner.setDropDownWidth(size_in_pixel);
0
source

Source: https://habr.com/ru/post/1719838/


All Articles