How to determine if a drop-down menu is displayed above or below the counter in android?

I am working on a design. what I want is when the spinner popup falls below the spinner, I want to use a popupbackground image different, and when it pops up above the spinner, I want to use popup background different

here is my xml code:

<Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:spinnerMode="dropdown" android:popupBackground="@drawable/spinnerbottombg" android:overlapAnchor="false" android:drawSelectorOnTop="false" /> 

Now the question is, how can I find out that spinner opens a drop-down list above or below it

+8
android spinner
source share
1 answer

I will fit deep into PopupWindow and find that your requirement can be achieved with

StateListDrawable

The following codes will explain everything -

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.mmbarno.dummyalertdialog.MainActivity"> <Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:spinnerMode="dropdown" android:overlapAnchor="false" android:drawSelectorOnTop="false" /> </RelativeLayout> 

popup_bg_above.xml

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#FF4081" /> </shape> 

popup_bg_below.xml

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#3F51B5" /> </shape> 

Finally, in MainActivity.java

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setPopupBackgroundDrawable(getPopupBg()); populateSpinner(); } private void populateSpinner() { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } private StateListDrawable getPopupBg() { StateListDrawable states = new StateListDrawable(); int identifier = Resources.getSystem().getIdentifier("state_above_anchor", "attr", "android"); states.addState(new int[] {identifier}, ContextCompat.getDrawable(this, R.drawable.popup_bg_below)); states.addState(new int[]{}, ContextCompat.getDrawable(this, R.drawable.popup_bg_above)); return states; } 

Hope your requirement is met. I tested it in different scenarios along with ScrollView. And it works great.

Popup below

Popup above

+10
source share

All Articles