PopupWindow的简单用法

首先创建弹出框的布局

layout_popupwindow

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e96f6f"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/popwindow_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="弹出窗的标题" />

    <TextView
        android:id="@+id/popwindow_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="弹出窗的内容" />
</LinearLayout>

在Activity中点击按钮显示弹出框

btnShowWindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //实例化弹窗布局
                View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_popupwindow, null);
                //传入弹窗布局和宽高,创建popupwindow对象,
                PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, 500, true);
                //显示在按钮下面
                popupWindow.showAsDropDown(view, 100, 100);
            }
        });

显示在不同方向

使用showAtLocation(View parent,int gravity,int xoff,int yoff)确定位置

示例:在点击按钮的左 

popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

第二个参数是方向。

第三个和第四个参数分别代表x和y轴的偏移距离。

如果要显示在任意的位置,方向传入Gravity.NO_GRAVITY即可。

示例:显示在按钮正上方

        //获取按钮的x和y坐标
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        //弹窗的x轴不变,y轴减去弹窗自身的高度,刚好就在按钮上面了
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0], location[1] - popupWindow.getHeight());


为popupwindow加入动画

很多应用的弹窗动画都是从下往上弹出来


在anim目录创建动画xml

anim_in

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="300"
        android:fromYDelta="100%"
        android:toYDelta="0" />
    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>


在style中创建样式,设置windowEnterAnimation的值为动画xml

    <style name="window_anim_in">
        <!--显示布局的动画-->
        <item name="android:windowEnterAnimation">@anim/anim_in</item>
    </style>


给popupwindows设置此样式

popupWindow.setAnimationStyle(R.style.window_anim_in);
注意:必须在show方法之前设置,否则无效 

猜你喜欢

转载自blog.csdn.net/adojayfan/article/details/53154070