在任意指定view的位置弹出popupWindow

在指定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的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="108dp"
    android:layout_height="47dp" >

    <TextView
        android:id="@+id/play_again_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="7dp"
        android:paddingBottom="7dp"
        android:textColor="@color/white"
        android:text="Play the game again"
        android:textSize="14sp" />

</RelativeLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值