Nitish
Nitish

Reputation: 3155

Android: Set popup window width same as achor view width

I am using constraint layout in which I have arranged views using flow.
These views are added dynamically.
enter image description here

On clicking any of view a popup window should open like shown in the illustration below:
enter image description here

I have managed to show the popup window but it is not taking complete width of anchor view. This is how it is looking right now:

enter image description here

This is the snippet from my code which shows the popup window

anchorView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val width = anchorView.measuredWidth
val height = ViewGroup.LayoutParams.WRAP_CONTENT

val focusable = true
val popupWindow = PopupWindow(popupCardBinding.root, width, height, focusable)
popupWindow.showAsDropDown(anchorView)

How can I make it's width same as anchorView's width?

Upvotes: 3

Views: 557

Answers (2)

WHOATEMYNOODLES
WHOATEMYNOODLES

Reputation: 2643

I had the exact same problem and couldn't find a good answer after searching for a while. I ended up passing the Anchor View to the PopupWindow's constructor.

public TestPopupWindow(Context context, View anchorView) {
        super(context);
        this.context = context; 
        this.anchorView = anchorView;
        createView();
}

And setting the width during the view inflation.

private void createView() {
        View view = View.inflate(context, R.layout.popup_window_layout, null); 
        this.setWidth(anchorView.getWidth());
        setContentView(view);
}

Simple and works for me

Upvotes: 0

Amin
Amin

Reputation: 1028

I'm not sure where you're calling measure for the anchor view, but try measuring after the view has been drawn - using UNSPECIFIED doesn't always return the correct values, if you use measure too early:

anchorView.post {
  anchorView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
  val width = anchorView.measuredWidth
  val height = ViewGroup.LayoutParams.WRAP_CONTENT

  val focusable = true
  val popupWindow = PopupWindow(popupCardBinding.root, width, height, focusable)
  popupWindow.showAsDropDown(anchorView)
}

If it doesn't work, try showing more code about how and when anchorView is created

Upvotes: 0

Related Questions