Android PopupWindow

Android PopupWindow


构造方法

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

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

还可以

public PopupWindow (Context context)

或者

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

或者

public PopupWindow(View contentView)

其中第一种最省事,构造函数中设置了要显示的View,宽度 ,高度以及是否能获得焦点。以上是几种用的比较常见的构造方法。


改变PopupWindow的视图内容

可以通过

public void setContentView(View contentView)

来改变popup的显示内容,也可以用来初始化PopupWindow的View,比如使用构造函数public PopupWindow (Context context)获得的Popupwindow就只能用setContentView来设置内容。

PopupWindow popupWindow = new PopupWindow(context);
popupWindow.setContentView(contentview);


获得PopupWindow的视图内容

public View getContentView()


显示PopupWindow

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

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

  • showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移

其实我发现showAtLocation的parent参数可以很随意,只要是activity中的view都可以。


大小:

有两种方法设置PopupWindow的大小:

调用有宽高参数的构造函数:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentview = inflater.inflate(R.layout.popup_process, null);
PopupWindow popupWindow = new PopupWindow(contentview,LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

通过setWidthsetHeight设置

PopupWindow popupWindow = new PopupWindow(contentview);
popupWindow.setWidth(LayoutParams.WRAP_CONTENT);           
popupWindow.setHeight(LayoutParams.WRAP_CONTENT);

两种办法是等效的,不管采用何种办法,必须设置宽和高,否则不显示任何东西.

这里的WRAP_CONTENT可以换成fill_parent 也可以是具体的数值,它是指PopupWindow的大小,也就是contentview的大小,注意popupwindow根据这个大小显示你的View,如果你的View本身是从xml得到的,那么xml的第一层view的大小属性将被忽略。相当于popupWindowwidthheight属性直接和第一层View相对应。

设想下面一种场景:

popupWindow 设置为WRAP_CONTENT ,我想得到的是一个宽150dip 80dippopupwindow,需要额外加一层

LinearLayout ,这个LinearLayout layout_widthlayout_height为任意值。而我们真正想显示的View 放在第二层,并且  android:layout_width="150.0dip"  android:layout_height="80.0dip"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
>
    <LinearLayout
        android:background="@drawable/shape_ret_loading_bg"
        android:layout_width="150.0dip"
        android:layout_height="80.0dip"
        android:orientation="vertical"
        android:gravity="center"
    >
        <TextView
            android:textSize="14dip"
            android:textColor="@color/white"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10.0dip"
            android:text="加载中..."
        />
    </LinearLayout>
</LinearLayout>


PopUpWindow的焦点:

setFocusable设置PopupWindow的焦点,一般资料对此的解释都是:是否让Popupwindow可以点击但是这揭示了本质却与直观现象不符。实际上,

如果:

setFocusable(true);

PopUpWindow本身可以看作一个类似于模态对话框的东西(但有区别),PopupWindow弹出后,所有的触屏和物理按键都有PopupWindows处理。其他任何事件的响应都必须发生在PopupWindow消失之后, (home  等系统层面的事件除外)。比如这样一个PopupWindow出现的时候,按back键首先是让PopupWindow消失,第二次按才是退出activity,准确的说是想退出activity你得首先让PopupWindow消失,因为不并是任何情况下按back  PopupWindow都会消失,必须在PopupWindow设置了背景的情况下 。

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

setFocusable(false);

PopUpWindow只是一个浮现在当前界面上的view而已,不影响当前界面的任何操作。

是一个“没有存在感”的东西。

一般情况下setFocusable(true);


点击空白处的时候让PopupWindow消失

关于PopupWindow最搞笑的地方是setOutsideTouchable方法,原本以为如果你setOutsideTouchable(true)则点击PopupWindow之外的地方PopupWindow会消失,其实这玩意儿好像一点用都没有。

要让点击PopupWindow之外的地方PopupWindow消失你需要调用setBackgroundDrawable(new BitmapDrawable());

设置背景,为了不影响样式,这个背景是空的。还可以这样写,觉得这样要保险些:

setBackgroundDrawable(new ColorDrawable(0x00000000));

背景不为空但是完全透明。如此设置还能让PopupWindow在点击back的时候消失。其实一直觉得很奇怪,不明白为什么一个背景会影响点击事件,只知道这样用可行。

后来在评论中有人回答了此问题:


如果有背景,则会在contentView外面包一层PopupViewContainer之后作为mPopupView,如果没有背景,则直接用contentView作为mPopupView。

而这个PopupViewContainer是一个内部私有类,它继承了FrameLayout,在其中重写了Key和Touch事件的分发处理

详情见:http://www.cnblogs.com/mengdd/p/3569127.html  



PopupWindow实现一个真正的模态对话框

刚才说到“popupWindow.setFocusable(true);

PopUpWindow本身可以看作一个类似于模态对话框的东西

其实这句话有一些细微的错误,在android中一个模态对话框应该是这样的:

阻止屏幕上的其他View事件,且点击PopupWindow外面不会消失,但是能响应back事件(点击back消失),所以如果要让

PopupWindow有模态对话框的表现,则不能调用setBackgroundDrawable,因为setBackgroundDrawable会让点击PopupWindow外面PopupWindow消失。但是如果不调用setBackgroundDrawable则点击back键也不会消失,比模态对话框还变态。不过还是有解决的办法:

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentview = inflater.inflate(R.layout.popup_process, null);
contentview.setFocusable(true); // 这个很重要
contentview.setFocusableInTouchMode(true);
final PopupWindow popupWindow = new PopupWindow(contentview,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(false);
contentview.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            popupWindow.dismiss();                                              
            return true;
        }
        return false;
    }
});
popupWindow.showAtLocation(view,  Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);


其中要注意的是PopupWindow 的视图contentview的设置,contentview.setFocusable(true);  这个很重要,注意不是PopupWindowsetFocusable,同时setOnKeyListener也是contentview调用的,而不是PopupWindowsetOnKeyListener方法中的代码很好理解,但是为啥是contentview调用就不是很清楚了,貌似没人去研究。其实为了是代码的相关性更低contentview.setOnKeyListener可以用popupWindow.getContentView.setOnKeyListener来代替。

话说如果PopupWindow需要如此这番周折才能实现一个模态对话框何不直接用Dialog呢?其实我只是将这些现象讲清楚,你可以根据这些知识将PopupWindow 应用在很苛刻的场景中。


PopupWindow的动画

很多时候我们把PopupWindow用作自定义的菜单,需要一个从底部向上弹出的效果,这就需要为PopupWindow添加动画。

设置动画的方法:

 
 
  1. public void setAnimationStyle(int animationStyle)

在res/value/styles.xml添加一个sytle

<style name="anim_menu_bottombar">
    <item name="android:windowEnterAnimation">@anim/menu_bottombar_in</item>
    <item name="android:windowExitAnimation">@anim/menu_bottombar_out</item>
</style>

在工程res下新建anim文件夹,在anim文件夹先新建两个xml文件

menu_bottombar_in.xml

<?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>

menu_bottombar_out.xml

<?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>

mPopupWindow.setAnimationStyle(R.style.menu_anim_bottombar);

=============================popupWindow 显示=================================

popupWindow 在控件的各个方向上的显示(上、下、左、右),主要用到popupWindow 的showAtLocation()方法:

在控件的上方:

[java]  view plain  copy
  1. private void showPopUp(View v) {  
  2.         LinearLayout layout = new LinearLayout(this);  
  3.         layout.setBackgroundColor(Color.GRAY);  
  4.         TextView tv = new TextView(this);  
  5.         tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  
  6.         tv.setText("I'm a pop -----------------------------!");  
  7.         tv.setTextColor(Color.WHITE);  
  8.         layout.addView(tv);  
  9.   
  10.         popupWindow = new PopupWindow(layout,120,120);  
  11.           
  12.         popupWindow.setFocusable(true);  
  13.         popupWindow.setOutsideTouchable(true);  
  14.         popupWindow.setBackgroundDrawable(new BitmapDrawable());  
  15.           
  16.         int[] location = new int[2];  
  17.         v.getLocationOnScreen(location);  
  18.           
  19.         popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-popupWindow.getHeight());  
  20.     }  

在控件的其他方向上显示只需修改最后一行代码即可,如:

下方:popupWindow.showAsDropDown(v);

左边:

[java]  view plain  copy
  1. popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]-popupWindow.getWidth(), location[1]);  
右边:
[html]  view plain  copy
  1. popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]+v.getWidth(), location[1]);  

在我们开发App的过程中,难免会有需求涉及到PopupWindow的使用。

最基本的创建方式:

window = new PopupWindow(contentView, 
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);

最后一个参数为boolean类型,即设置PopupWindow焦点,与PopupWindow的setFocusable(focusable)方法等同。

设置为true时,PopupWindow会处理事件。设置为false时,PopupWindow不获取焦点,事件上传到Activity。

所以,当设置为false时,点击返回键,PopupWindow不会隐藏,Activity会直接退出。

一般情况下,我们都会将其设置为true。

使用PopupWIndow时的情景状态又会分为两种情况:

(1)显示PopupWindow,点击内容区域以外的地方时,PopupWindow不隐藏。

(2)显示PopupWindow,点击内容区域以外的地方时,PopupWindow隐藏。

关于设置内容区域以外的点击状态,从PopupWindow源码中可以看到,PopupWindow为我们提供了setOutsideTouchable(boolean touchable)方法:

/**
* <p>Controls whether the pop-up will be informed of touch events outside
* of its window. This only makes sense for pop-ups that are touchable
* but not focusable, which means touches outside of the window will
* be delivered to the window behind. The default is false.</p>
*
* <p>If the popup is showing, calling this method will take effect only
* the next time the popup is shown or through a manual call to one of
* the {@link #update()} methods.</p>
*
* @param touchable true if the popup should receive outside
* touch events, false otherwise
*
* @see #isOutsideTouchable()
* @see #isShowing()
* @see #update()
*/

public void setOutsideTouchable(boolean touchable) {
mOutsideTouchable = touchable;
}

此时,我们来实现第一种情景:即点击,PopupWindow不隐藏:

window.setOutsideTouchable(false);
window.setBackgroundDrawable(null);

setBackgroundDrawable设置为null时,PopupWindow的单击和Key事件都不能起作用。此时问题来了,在点击返回键时,没有任何反应。PopupWindow不能关闭。

解决办法:

设置contentView,即PopupWindow的contentView:

contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
contentView.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
window.dismiss();
return true;
}
return false;
}
});


为PopupWindow的内容View添加Key的监听事件,当为返回键时,让PopupWindow隐藏。ok,完美解决!

第二种情景:

window.setOutsideTouchable(true);
window.setBackgroundDrawable(new ColorDrawable(0x000000));

setBackgroundDrawable设置了一个背景,此时PopupWindow的外部单击和key事件都会起作用(原理就是当我们设置了背景时,PopupWindow源码中会生成一个FrameLayout布局,同时为该布局添加单击和key事件)。

所以,此时点击内容区域外部时,PopupWindow会消失,并且点击返回键,PopupWindow也会消失。

希望你在平常的项目中使用的666!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值