安卓开发之PopupWindow

1)简介

PopupWindow是Android上自定义弹出窗口,与AlertDialog相比,PopupWindow更加灵活,能够灵活的指定自定义窗口的显示位置

2)用法

PopupWindow的构造函数

public PopupWindow(View contentView, int width, int height, boolean focusable)

contentView为要显示的view,width和height为宽和高,值为像素值,也可以是MATCHT_PARENT和WRAP_CONTENT。

focusable为是否可以获得焦点,这是一个很重要的参数,也可以通过

public void setFocusable(boolean focusable)

来设置,如果focusable为false,在一个Activity弹出一个PopupWindow,按返回键,由于PopupWindow没有焦点,会直接退出Activity。如果focusable为true,PopupWindow弹出后,所有的触屏和物理按键都有PopupWindows处理。

如果PopupWindow中有Editor的话,focusable要为true。

 

如果需要设置点击空白处的时候PopupWindow消失需要添加下面三行代码

 

mPopupWindow.setTouchable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

 

这一行代码将PopupWindow以控件v为基准在该控件的正左方以向下弹出的动画的形式显示出来
mPopupWindow.showAsDropDown(View v);

如需使用其他弹出弹入动画,可自定义进入动画和推出动画。

例:从下往上的进入动画

 

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

    <translate
        android:duration="250"
        android:fromYDelta="100.0%"
        android:toYDelta="0.0" />

</set>
 

 

从上往下的退出动画
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="250"
        android:fromYDelta="0.0"
        android:toYDelta="100%" />

</set>
 
建立一个style
<style name="anim_menu_bottombar">
        <item name="android:windowEnterAnimation">@anim/menu_bottombar_in</item>
        <item name="android:windowExitAnimation">@anim/menu_bottombar_out</item>    
</style>

最后在代码中

mPopWindow.setAnimationStyle(R.style.anim_menu_bottombar);  
即可

猜你喜欢

转载自blog.csdn.net/sinat_31841263/article/details/54605567