热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

AndroidPopupWindow用法解析

这篇文章主要为大家详细解析了AndroidPopupWindow用法,对PopupWindow源码进行分析,感兴趣的小伙伴们可以参考一下

PopupWindow使用

PopupWindow这个类用来实现一个弹出框,可以使用任意布局的View作为其内容,这个弹出框是悬浮在当前activity之上的。

PopupWindow使用Demo

这个类的使用,不再过多解释,直接上代码吧。
比如弹出框的布局: 

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

 

Activity的布局中只有一个按钮,按下后会弹出框,Activity代码如下: 

package com.example.hellopopupwindow;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

public class MainActivity extends Activity {

 private Context mCOntext= null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mCOntext= this;

  Button button = (Button) findViewById(R.id.button);
  button.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

    showPopupWindow(view);
   }
  });
 }

 private void showPopupWindow(View view) {

  // 一个自定义的布局,作为显示的内容
  View cOntentView= LayoutInflater.from(mContext).inflate(
    R.layout.pop_window, null);
  // 设置按钮的点击事件
  Button button = (Button) contentView.findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Toast.makeText(mContext, "button is pressed",
      Toast.LENGTH_SHORT).show();
   }
  });

  final PopupWindow popupWindow = new PopupWindow(contentView,
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);

  popupWindow.setTouchable(true);

  popupWindow.setTouchInterceptor(new OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {

    Log.i("mengdd", "onTouch : ");

    return false;
    // 这里如果返回true的话,touch事件将被拦截
    // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
   }
  });

  // 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
  // 我觉得这里是API的一个bug
  popupWindow.setBackgroundDrawable(getResources().getDrawable(
    R.drawable.selectmenu_bg_downward));

  // 设置好参数之后再show
  popupWindow.showAsDropDown(view);

 }

}

弹出框的布局中有一个TextView和一个Button,Button点击后显示Toast,如图: 

第一次实现的时候遇到了问题,就是弹出框不会在按下Back键的时候消失,点击弹框外区域也没有正常消失,搜索了一下,都说只要设置背景就好了。
然后我就找了个图片,果然弹框能正常dismiss了(见注释)。

PopupWindow源码分析

为了解答一下上面的问题,看看源码(最新API Level 19,Android 4.4.2)。

1.显示方法

显示提供了两种形式:

showAtLocation()显示在指定位置,有两个方法重载:

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

showAsDropDown()显示在一个参照物View的周围,有三个方法重载:

public void showAsDropDown(View anchor)
public void showAsDropDown(View anchor, int xoff, int yoff)
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) 

最后一种带Gravity参数的方法是API 19新引入的。
弹出的方法中首先需要preparePopup() ,最后再invokePopup()
prepare的方法中可以看到有无背景的分别: 

 /**
  * 

Prepare the popup by embedding in into a new ViewGroup if the * background drawable is not null. If embedding is required, the layout * parameters' height is mnodified to take into account the background's * padding.

* * @param p the layout parameters of the popup's content view */ private void preparePopup(WindowManager.LayoutParams p) { if (mCOntentView== null || mCOntext== null || mWindowManager == null) { throw new IllegalStateException("You must specify a valid content view by " + "calling setContentView() before attempting to show the popup."); } if (mBackground != null) { final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams(); int height = ViewGroup.LayoutParams.MATCH_PARENT; if (layoutParams != null && layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) { height = ViewGroup.LayoutParams.WRAP_CONTENT; } // when a background is available, we embed the content view // within another view that owns the background drawable PopupViewContainer popupViewCOntainer= new PopupViewContainer(mContext); PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height ); popupViewContainer.setBackgroundDrawable(mBackground); popupViewContainer.addView(mContentView, listParams); mPopupView = popupViewContainer; } else { mPopupView = mContentView; } mPopupViewInitialLayoutDirectiOnInherited= (mPopupView.getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT); mPopupWidth = p.width; mPopupHeight = p.height; }

2.背景是否为空对Touch事件的影响
如果有背景,则会在contentView外面包一层PopupViewContainer之后作为mPopupView,如果没有背景,则直接用contentView作为mPopupView。
而这个PopupViewContainer是一个内部私有类,它继承了FrameLayout,在其中重写了Key和Touch事件的分发处理: 

 @Override
  public boolean dispatchKeyEvent(KeyEvent event) {
   if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
    if (getKeyDispatcherState() == null) {
     return super.dispatchKeyEvent(event);
    }

    if (event.getAction() == KeyEvent.ACTION_DOWN
      && event.getRepeatCount() == 0) {
     KeyEvent.DispatcherState state = getKeyDispatcherState();
     if (state != null) {
      state.startTracking(event, this);
     }
     return true;
    } else if (event.getAction() == KeyEvent.ACTION_UP) {
     KeyEvent.DispatcherState state = getKeyDispatcherState();
     if (state != null && state.isTracking(event) && !event.isCanceled()) {
      dismiss();
      return true;
     }
    }
    return super.dispatchKeyEvent(event);
   } else {
    return super.dispatchKeyEvent(event);
   }
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
   if (mTouchInterceptor != null && mTouchInterceptor.onTouch(this, ev)) {
    return true;
   }
   return super.dispatchTouchEvent(ev);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   final int x = (int) event.getX();
   final int y = (int) event.getY();
   
   if ((event.getAction() == MotionEvent.ACTION_DOWN)
     && ((x <0) || (x >= getWidth()) || (y <0) || (y >= getHeight()))) {
    dismiss();
    return true;
   } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
    dismiss();
    return true;
   } else {
    return super.onTouchEvent(event);
   }
  }

由于PopupView本身并没有重写Key和Touch事件的处理,所以如果没有包这个外层容器类,点击Back键或者外部区域是不会导致弹框消失的。

补充Case: 弹窗不消失,但是事件向下传递
如上所述:
设置了PopupWindow的background,点击Back键或者点击弹窗的外部区域,弹窗就会dismiss.
相反,如果不设置PopupWindow的background,那么点击back键和点击弹窗的外部区域,弹窗是不会消失的.
那么,如果我想要一个效果,点击外部区域,弹窗不消失,但是点击事件会向下面的activity传递,比如下面是一个WebView,我想点击里面的链接等.

研究了半天,说是要给Window设置一个Flag,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
看了源码,这个Flag的设置与否是由一个叫mNotTouchModal的字段控制,但是设置该字段的set方法被标记为@hide。
所以要通过反射的方法调用: 

   /**
  * Set whether this window is touch modal or if outside touches will be sent
  * to
  * other windows behind it.
  *
  */
 public static void setPopupWindowTouchModal(PopupWindow popupWindow,
   boolean touchModal) {
  if (null == popupWindow) {
   return;
  }
  Method method;
  try {

   method = PopupWindow.class.getDeclaredMethod("setTouchModal",
     boolean.class);
   method.setAccessible(true);
   method.invoke(popupWindow, touchModal);

  }
  catch (Exception e) {
   e.printStackTrace();
  }

 }

然后在程序中:
UIUtils.setPopupWindowTouchModal(popupWindow, false);

该popupWindow外部的事件就可以传递给下面的Activity了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 解决JAX-WS动态客户端工厂弃用问题并迁移到XFire
    在处理Java项目中的JAR包冲突时,我们遇到了JaxWsDynamicClientFactory被弃用的问题,并成功将其迁移到org.codehaus.xfire.client。本文详细介绍了这一过程及解决方案。 ... [详细]
  • Android 九宫格布局详解及实现:人人网应用示例
    本文深入探讨了人人网Android应用中独特的九宫格布局设计,解析其背后的GridView实现原理,并提供详细的代码示例。这种布局方式不仅美观大方,而且在现代Android应用中较为少见,值得开发者借鉴。 ... [详细]
  • 本文总结了2018年的关键成就,包括职业变动、购车、考取驾照等重要事件,并分享了读书、工作、家庭和朋友方面的感悟。同时,展望2019年,制定了健康、软实力提升和技术学习的具体目标。 ... [详细]
  • 在计算机技术的学习道路上,51CTO学院以其专业性和专注度给我留下了深刻印象。从2012年接触计算机到2014年开始系统学习网络技术和安全领域,51CTO学院始终是我信赖的学习平台。 ... [详细]
  • CSS 布局:液态三栏混合宽度布局
    本文介绍了如何使用 CSS 实现液态的三栏布局,其中各栏具有不同的宽度设置。通过调整容器和内容区域的属性,可以实现灵活且响应式的网页设计。 ... [详细]
  • Linux 系统启动故障排除指南:MBR 和 GRUB 问题
    本文详细介绍了 Linux 系统启动过程中常见的 MBR 扇区和 GRUB 引导程序故障及其解决方案,涵盖从备份、模拟故障到恢复的具体步骤。 ... [详细]
  • 本文介绍了如何使用jQuery根据元素的类型(如复选框)和标签名(如段落)来获取DOM对象。这有助于更高效地操作网页中的特定元素。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 理解存储器的层次结构有助于程序员优化程序性能,通过合理安排数据在不同层级的存储位置,提升CPU的数据访问速度。本文详细探讨了静态随机访问存储器(SRAM)和动态随机访问存储器(DRAM)的工作原理及其应用场景,并介绍了存储器模块中的数据存取过程及局部性原理。 ... [详细]
  • 几何画板展示电场线与等势面的交互关系
    几何画板是一款功能强大的物理教学软件,具备丰富的绘图和度量工具。它不仅能够模拟物理实验过程,还能通过定量分析揭示物理现象背后的规律,尤其适用于难以在实际实验中展示的内容。本文将介绍如何使用几何画板演示电场线与等势面之间的关系。 ... [详细]
  • 本文介绍如何通过Windows批处理脚本定期检查并重启Java应用程序,确保其持续稳定运行。脚本每30分钟检查一次,并在需要时重启Java程序。同时,它会将任务结果发送到Redis。 ... [详细]
author-avatar
白小蛮
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有