Most examples out there specify exactly the width and height of the popup window. I want them to be WRAP_CONTENT - since the content is dinamically determined, so in the constructor I set -2 for both width and height and show it via showAsDropDown(View anchor)
Doing this, the popup is always drawn below the anchor view, which means it can be drawn offscreen. The following snippet demonstrates the problem. Try clicking on the last TextView and you won't see any PopupWindow, since it's shown outside of the windows bounds. Why doesn't it work? I remark that specifying dimension explicitly (for example 200, 100) doesn't trigger the problem. Try it yourself
package com.zybnet.example.popupdemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
public class PopupDemoActivity extends Activity implements OnClickListener {
private PopupWindow popup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// -2 means WRAP_CONTENT THIS TRIGGERS THE PROBLEM
popup = new PopupWindow(getPopupContent(), -2, -2);
// When you specify the dimensions everything goes fine
//popup = new PopupWindow(getPopupContent(), 200, 100);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// FILL_PARENT and same layout weight for all children
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1, 1);
for (int i = 0; i < 10; i++) {
TextView tv = new TextView(this);
tv.setText("Click to show popup");
tv.setOnClickListener(this);
layout.addView(tv, params);
}
setContentView(layout);
}
@Override
public void onClick(View view) {
popup.dismiss();
popup.showAsDropDown(view);
}
private View getPopupContent() {
TextView popupContent = new TextView(this);
popupContent.setText("Some text here");
popupContent.setTextColor(Color.parseColor("#5000ae"));
popupContent.setBackgroundColor(Color.parseColor("#ff00ff"));
popupContent.setPadding(10, 20, 20, 10);
return popupContent;
}
}