美文网首页
PopupWindow 学习笔记

PopupWindow 学习笔记

作者: feifei_fly | 来源:发表于2018-04-01 21:31 被阅读0次

今天学习了PopupWindow,正好做个笔记记录一下,以便查阅。

一、Android 中的弹框 分为两种AlertDialog和PopupWindow

1、AlertDialog 弹框位置是固定的,并且是非阻塞性的。弹窗显示时,当前线程不会阻塞。
2、PopupWindow
弹框的位置可是任意指定,并且会阻塞线程

二 PopupWindow

使用PopupWindow分为两个步骤:

1. 初始化PopupWindow

      popupWindow = new PopupWindow(this);
//            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
//            popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setWidth(100*5);
            popupWindow.setHeight(400);
            View inlatView = LayoutInflater.from(this).inflate(R.layout.include_popupview,null);
            popupWindow.setContentView(inlatView);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
            popupWindow.setOutsideTouchable(false);
            popupWindow.setFocusable(true);
  • 其中 popupWindow.setWidth()和popWindow.setHeight()指定popupWindow显示的尺寸。既可以是具体的尺寸,也可以是WRAP_CONTENT 和MATH_CONTENT
  • popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000)); 设置popupView的背景颜色
  • PopupView中如何有EditView,必须设置popupWindow.setFocusable(true);

2. 显示PopupWindow有两种显示方式:

(1)相对于某个控件(以下拉组件的形式)显示
  • showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移

  • showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置(正左下方),有偏移

  • showAsDropDown(View anchor, int xoff, int yoff, int gravity) :相对于某个控件anchor以下拉菜单方式显示,有偏移 xoff、yoff,可以指定gravity

//显示在view控件的正左上方

 popupWindow.showAsDropDown(view,0,0, Gravity.TOP);

//显示在view控件的正左下方

 popupWindow.showAsDropDown(view,100,100, Gravity.BOTTOM);
  • (2)相对于父控件的位置显示(可以指定gravity ,如Gravity.CENTER 在父控件中心显示,下方Gravity.BOTTOM 在父控件下方显示),可以有偏移 也可以无偏移
     popupWindow.showAtLocation(view, Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL,300,300);

可以指定popupWindow的进入进出的动画

 popupWindow.setAnimationStyle(R.style.AnimationFade);//指定进出动画
 popupWindow.showAtLocation(view, Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL,300,300);

in_lefttoright.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    >
    <translate android:fromXDelta="-100%"
        android:toXDelta="0"
        />
</set>

out_righttoleft.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    >
    <translate android:fromXDelta="0"
        android:toXDelta="-100%"
        />
</set>

style.xml

<resources>
    <style name="AnimationFade">
        <item name="android:windowEnterAnimation">@anim/in_lefttoright</item>
        <item name="android:windowExitAnimation">@anim/out_righttoleft</item>
    </style>
</resources>

相关文章

网友评论

      本文标题:PopupWindow 学习笔记

      本文链接:https://www.haomeiwen.com/subject/gsnacftx.html