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.


MMBarno
source share