在指定view处弹出弹窗,主要需要获取指定view的位置,可以通过这种方式:
int[] xy = new int[2];
view.getLocationInWindow(xy);
然后在showAtLocation时设置下位置即可:
mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
xy[0] + (DimenUtils.dp2px(width) - view.getWidth()) / 2, xy[1] - DimenUtils.dp2px(50));
或者使用这种方式:
mPopupWindow.showAsDropDown(view, 100, 100);
上面两种方式都是设置一个锚点view,在这个锚点view的上方或者下方,具体设置位置参数调整即可。
整体代码如下:
private void showPlayAgainPopup(View view) {
View contentView = LayoutInflater.from(mActivity).inflate(R.layout.result_page_popup_window, null);
TextView popupText = contentView.findViewById(R.id.play_again_text);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Play the game \nagain");
popupText.setText(spannableStringBuilder);
mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
mPopupWindow.setTouchable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
mPopupWindow.setBackgroundDrawable(mActivity.getResources().getDrawable(R.color.popup_background));
int width = mPopupWindow.getWidth();
int[] xy = new int[2];
view.getLocationInWindow(xy);
mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
xy[0] + (DimenUtils.dp2px(width) - view.getWidth()) / 2, xy[1] - DimenUtils.dp2px(50));
// mPopupWindow.showAsDropDown(view, 100, 100);
}
自定义view的布局如下: