I'm creating a ListPopupWindow
like this:
final ListPopupWindow insidelistPopupWindow = new ListPopupWindow(view.getContext());
insidelistPopupWindow.setContentWidth(getResources().getDimensionPixelSize(R.dimen.popupNewWidth));
insidelistPopupWindow.setHeight(getResources().getDimensionPixelSize(R.dimen.size300dp));
insidelistPopupWindow.setVerticalOffset(getResources().getDimensionPixelSize(R.dimen.size0dp));
insidelistPopupWindow.setHorizontalOffset(getPoupHorizontalOffset());
//set adapter...
insidelistPopupWindow.setAnchorView(view);
insidelistPopupWindow.show();
I tried to do simple math
public int getPoupHorizontalOffset() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
return getResources().getDimensionPixelSize(R.dimen.popupNewWidth) - width/2;
}
to center it horizontally. It worked on my phone but not on others, so I suspect something is wrong about my asumptions. But I also suspect there's a better way of solving this.
How do I simply center something horizontally programatically?
PS: the same ListPopupWindow but with different number of elements is getting placed on different positions on screen. Why this happens?
UPDATE:
Based on the answer below,
I tried
listPopupWindow.setAnchorView(view);
listPopupWindow.setContentWidth(getResources().getDimensionPixelSize(R.dimen.popupNewWidth));
listPopupWindow.setHeight(getResources().getDimensionPixelSize(R.dimen.size250dp));
listPopupWindow.setVerticalOffset(getResources().getDimensionPixelSize(R.dimen.size50dp));
listPopupWindow.setHorizontalOffset(listPopupWindowWidth(view, listPopupWindow));
listPopupWindow.setPromptPosition(ListPopupWindow.POSITION_PROMPT_ABOVE);
and did
int listPopupWindowWidth(View view, ListPopupWindow listPopupWindow) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int horizontalOffset = (screenWidth / 2) - (getRelativeLeft(view) + listPopupWindow.getWidth() / 2);
return horizontalOffset;
}
private int getRelativeLeft(View view) {
if (view.getParent() == view.getRootView()) {
return view.getLeft();
} else {
return view.getLeft() + getRelativeLeft((View) view.getParent());
}
}
but my popup is slightly to the left, not exactly centered. My view is in landscape mode, does it have anything to do with it? I tried changing width by height but it didn't work