Android中PopupWindow的使用(二)

很久前,写过一篇关于PopupWindow使用的文章。今天,接着总结一下,PopupWindow使用方面的一些知识。

一、showAtLocation方法的使用。

使用该方法,我们可以在指定的位置显示PopupWindow,更加灵活,能满足我们的更多需求。

public void showAtLocation (View parent, 
                int gravity, 
                int x, 
                int y)

四个参数含义分别为:

parent:相对的父视图,也就是说我们的PopupWindow的显示位置是以这个视图为基准。

gravity:可以理解为用于控制其显示方式,如果我们不想使用这一项,则直接用Gravity.NO_GRAVITY即可。

x:PopupWindow在x轴方向上的偏移量。

y:PopupWindow在y轴方向上的偏移量。

通过控制这四个参数,我们可以将PopupWindow指定在我们想要的位置上显示。

二、PopupWindow(View contentView, int width, int height, boolean focusable)

PopupWindow的这个构造方法。比如,

reportSearchPopupWindow = new PopupWindow(view_report_search_popup_window, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);

其中最后一个参数,如果为true,那么点击屏幕的空白处,可以让PopupWindow消失;如果为false,那么点击屏幕的空白处,不可以让PopupWindow消失。

三、我们可以给PopupWindow设置显示和消失的动画。实现方式如下:

1、我们分别写一个PopupWindow显示和消失的动画。

popup_window_enter.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300">

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"/>

    <scale
        android:fromXScale="1.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:pivotX="100%"
        android:pivotY="0"/>
</set>
popup_window_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300">

    <alpha
        android:fromAlpha="1"
        android:toAlpha="0"/>

    <scale
        android:fromXScale="1.0"
        android:toXScale="1.0"
        android:fromYScale="1.0"
        android:toYScale="0.0"
        android:pivotX="100%"
        android:pivotY="0"/>
</set>

2、我们写一个样式。

    <style name="PopupWindowAnimation" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/popup_window_enter</item>
        <item name="android:windowExitAnimation">@anim/popup_window_exit</item>
    </style>

3、

reportSearchPopupWindow.setAnimationStyle(R.style.PopupWindowAnimation);

至此,就搞定了。

四、setOnDismissListener方法的使用。

有时我们需要监听PopupWindow消失,在PopupWindow消失后,执行某些操作。这时我们就用到了setOnDismissListener

实现如下:

         reportSearchPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        iv_high_search.setImageResource(R.mipmap.down_arrow);
                    }
                });

猜你喜欢

转载自blog.csdn.net/zdj_Develop/article/details/81315983