Skip to content

[Solved] Android PopupWindow positioning with not fully visible view

PopupWindow is a very useful class for showing customized popups on particular locations of a view or a view group. It can appear as a floating container on a view or activity. For example, You can simply show a custom layout inflated PopupWindow over a view by using the below code.

PopupWindow popup = new PopupWindow(context); //Initialization
View layout = getLayoutInflater().inflate(R.layout.overflow_video,null); //Custom view for popupwindow
popup.setContentView(layout); //Setting the content view
popup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); //Height of window
popup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); //Width of window
popup.showAsDropDown(anchroView); //To show the popupwindow as a dropdown (Just like a tooltip)

Congrats, With this you can simply create a PopupWindow item as a dropdown to your view just like below image. The images were taken from my work application called Entri (https://entri.app/).


But the actual issue starts off when the anchoring view is visible partially. You have set the PopupWindow set as a drop down. So for partially visible views, PopupWindow won’t show since it goes off the screen area. The fix for this issue is to show the PopupWindow above the view. Luckily¬†the showAsDropDown() has another overloaded method with extra arguments like below,

showAsDropDown(View anchor, int xoff, int yoff)

 

This will accept the xOff and yOff values.It will display the content view in a popup window anchored to the bottom-left corner of the anchor view offset by the specified x and y coordinates.So we have to find out the PopupWindow’s new x and y positions.So for that, `view.getLocationInWindow(values)` will help us.Let’s look into the code,

int[] values = new int[2];
view.getLocationInWindow(values); //Getting location of view into values array
int positionOfIcon = values[1]; //Getting the height position
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int height = (displayMetrics.heightPixels * 2) / 3;
if (positionOfIcon > height) {
popup.showAsDropDown(view, 0, -320); //-320 is a constant,You can use extra logic
} else {
popup.showAsDropDown(view, 0, 0); //Show as usual
}

 

Now run your app and check whether the PopupWindow is showing for partially visible views or not.

Published inAndroidKotlinposts

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *