I\'m trying to use ListPopupWindow to show a list of strings via an ArrayAdapter
(eventually this will be a more complex custom adapter). Code is below. As shown in
You can actually get the anchorView's parent (since the actual anchorView is generally a button) and base your width from there. For example:
popup.setWidth(((View)anchor.getParent()).getWidth()/2);
That way you can get a flexible width.
Another solution is to set a 0dp height view in your layout xml to use as an anchor.
<View
android:id="@+id/popup_anchor"
android:layout_width="140dp"
android:layout_height="0dp"/>
then set the anchor view sometime before calling the show() method.
listPopupWindow.setAnchorView(popupAnchor);
listPopupWindow.show();
My approach to this.
Create a View
in your layout which functions as an anchor, with your dedicated width and position (Height 1 dp, width as you wish) (may be dynamic i.e. with ConstraintLayouts). Make it invisible (android:visibility=View.INIVISIBLE
).
<View
android:id="@+id/my_anchor"
android:layout_height="1dp"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="@id/list_item_order_list_app_compat_image_button_gallery"
app:layout_constraintStart_toEndOf="@id/list_item_order_list_material_button_map"
app:layout_constraintEnd_toEndOf="parent"
android:visibility="invisible"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
/>
Reference to this view in your viewAnchor
, (i.e with bindings):
listPopupWindow.anchorView = binding.myAnchor
I would just set a dimension in your dimen.xml file at 160dp or so:
<dimen name="overflow_width">160dp</dimen>
Then set your popup width using the getDimensionPixelSize method to convert into pixels:
int width = mContext.getResources().getDimensionPixelSize(R.dimen.overflow_width);
mListPopupWindow.setWidth(width);
That should keep the size density independent.
I think the best thing to use is the PopupMenu . example:
final PopupMenu popupMenu = new PopupMenu(mActivity, v);
popupMenu.getMenu().add("test");
popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
return true;
}
});
popupMenu.show();
I believe that your issue lies with your ArrayAdapter using simple_list_item_1. If you look at the source code for that element it has the property of
android:layout_width="match_parent"
If you look at the source here you can create your own new_list_item_1.xml with the same info but changing it to android:layout_width="wrap_content"
and then use that in your ArrayAdapter