您的位置:首页 > 运维架构

PopupWindow的使用

2015-09-19 02:06 501 查看

PopupWindow的使用

popupWindow常用于点击某个条目,弹出一个对话框.

1.首先我们需要自定义一个PopupWindow的布局文件,用于显示对话框中的内容.

2.然后我们需要在某个点击事件中将这个布局文件填充成一个View对象,并将PopupWindow创建出来,代码如下:

View contentView = getLayoutInflater().inflate(
                R.layout.popup_item, null);
popWindow = new PopupWindow(contentView, -2, -2);


创建popWindow时,需要设置PopupWindow的宽高,-2表示包裹内容,-1表示填充满父元素.

3.需要指定PopupWindow在当前屏幕上的显示位置,代码如下:

popWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP,90, 0);


第一个参数指定了PopupWindow的父View,第二个参数指定了PopupWindow的重心(基准点),最后两个参数就是指定了PopupWindow相对于基准点的X和Y坐标

这时我们的PopupWindow就已经可以显示出来了.

4.如果我们需要一个动画的显示效果,我们需要定义动画的各种属性,然后将动画添加给填充好的布局文件的View对象,代码如下:

private void popWindowAnim(View contentView) {
    // 播放动画
    ScaleAnimation scaleAnimation = new ScaleAnimation(0.5f, 1,
            0.5f, 1, Animation.RELATIVE_TO_SELF, 0,
            Animation.RELATIVE_TO_SELF, 0.5f);// 缩放动画
    scaleAnimation.setDuration(200);

    AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
    alphaAnimation.setDuration(200);

    AnimationSet animationSet = new AnimationSet(true);
    animationSet.addAnimation(scaleAnimation);
    animationSet.addAnimation(alphaAnimation);
    // 动画的填充其实就是将图片填充成一个动画,但是填充时需要一个背景
    contentView.startAnimation(animationSet);
}


填充动画实际上就是将图片填充成一个动画,但是填充时需要一个背景.

5.由于动画的显示是popWindow显示的,我们需要将背景设置给popWindow,并且设置背景必须放在showAtLocation之前进行,代码如下:

popWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));// 直接设置一个透明的背景


注意一:poppupWindow默认不响应焦点,如果想要popupWindow响应点击等事件,需要设置:

popWindow.setFocusable(true);


注意二: 在poppupWindow消失时需要手动关闭popupWindow,不关闭会导致poppupWindow的泄漏.

if (popWindow != null && popWindow.isShowing()) {
        popWindow.dismiss();
        popWindow = null;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: