好的,这就是我如何实现我想要做的事情。是否可以动态放置 PopupWindow,而不必费力调整边距等。
public void showPopup(View view, View parentView, final int getId, String getLbs){
int pWidth = 100;
int pHeight = 80;
int vHeight = parentView.getHeight(); //The listview rows height.
int[] location = new int[2];
view.getLocationOnScreen(location);
final View pView = inflater.inflate(R.layout.list_popup, null, false);
final PopupWindow pw = new PopupWindow(pView, pWidth, pHeight, false);
pw.setTouchable(true);
pw.setFocusable(true);
pw.setOutsideTouchable(true);
pw.setBackgroundDrawable(new BitmapDrawable());
pw.showAtLocation(view, Gravity.NO_GRAVITY, location[0]-(pWidth/4), location[1]+vHeight);
final EditText input = (EditText)pView.findViewById(R.id.Input);
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.i("Focus", "Focus Changed");
if (hasFocus) {
//Shows the keyboard when the EditText is focused.
InputMethodManager inputMgr = (InputMethodManager)RecipeGrainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
inputMgr.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
}
});
input.setText("");
input.requestFocus();
Log.i("Input Has Focus", "" + input.hasFocus());
pw.setOnDismissListener(new OnDismissListener(){
@Override
public void onDismiss() {
changeWeight(getId, Double.parseDouble(input.getText().toString()));
Log.i("View Dismiss", "View Dismissed");
}
});
pw.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
Log.i("Background", "Back Touched");
pw.dismiss();
return true;
}
return false;
}
});
}
pWidth 和 pHeight 是我选择的 PopupWindow 的大小,vHeight 是我从 onCreate 上下文收集的主父视图的高度。请记住,这不是精美的代码。我仍然需要添加一些东西,例如动画进出以及一个漂亮的小箭头或其他东西来显示与窗口关联的内容。 setBackgroundDrawable 非常重要,如果您不使用它,您将无法在框外单击来关闭它。
现在看来,很奇怪。我必须在框外单击两次才能关闭窗口。第一次单击似乎只是突出显示我的文本框,第二次单击实际上将其关闭。任何人都知道为什么会发生这种情况?