Android Spinner - How to place the down arrow as close as possible to the text if the parameters have different lengths?

The options in my counter have different lengths, and currently the drop-down arrow is located far to the right based on the longest option, as shown in the screenshot below.

enter image description here enter image description here

Is it possible to move the arrow down so that it is dynamically positioned based on the currently selected parameter?

Especially when the first option is just β€œEverything,” it looks strange when the down arrow is so far to the right.

Referring to the Google Translate app, where the down arrow is always next to its text: enter image description here enter image description here

+5
source share
3 answers

First set the Spinner background to @null to remove the default triangle:

<Spinner android:id="@+id/spinner_main" android:spinnerMode="dropdown" android:background="@null" android:layout_width="wrap_content" android:layout_height="match_parent"/> 

Then create a spinner_item_main.xml layout resource only with a TextView, which we can set with the ability to draw on its right side (you can download the arrow image from here ):

 <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textStyle="bold" android:gravity="left" android:textColor="@color/colorWhite" android:drawableRight="@drawable/ic_arrow_drop_down_white_24dp" /> 

Finally Install this layout resource, when you initialize Spinner, you can also provide the resource as a drop-down list (like what I did):

(I use kotlin)

 spinner_main.adapter = ArrayAdapter<String>(this, R.layout.spinner_item_main, objects).apply { setDropDownViewResource(R.layout.spinner_dropdown_view_main) } 

Do this! View this in My AP app

+7
source
 1) Set the background of spinner to @null <Spinner android:id="@+id/spinner" android:background="@null" android:layout_width="wrap_content" android:layout_height="wrap_content"/> 2) In the spinner adapter layout, create an Imageview to the right of Textview or whatever content is in there change the visibility of the imageview to "gone" 3)Override the onItemSelected method of the spinner in your activity, in the onItemSelected method, call the Imageview ImageView downArrow = (ImageView) view.findViewById(R.id.down_arrow); change its visibility to "visible" 
0
source

Translation @ ε°Ή 小雨 answer in java

  ArrayAdapter adapter = new ArrayAdapter<Category>(this,R.layout.spinner_item_main,objects); // creates new ArrayAdapter with custom textviews for all elements including the first one (which is what we want) adapter.setDropDownViewResource(R.layout.spinner_dropdown_view_main); // Modifies all the elements when you click on the dropdown spinner.setAdapter(adapter); // sets the adapter to the spinner 
0
source

All Articles