PopupWindow使用

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

PopupWindow使用Demo

  这个类的使用,不再过多解释,直接上代码吧。

  比如弹出框的布局:

 弹出框布局

  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的方法中可以看到有无背景的分别:

   /**
* <p>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.</p>
*
* @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了。

Reference

  http://developer.android.com/reference/android/widget/PopupWindow.html

PopupWindow使用的更多相关文章

  1. Android PopupWindow Dialog 关于 is your activity running 崩溃详解

    Android PopupWindow Dialog 关于 is your activity running 崩溃详解 [TOC] 起因 对于 PopupWindow Dialog 需要 Activi ...

  2. Android popupwindow使用心得(一)

    最近项目中好多地方用到popupwindow,感觉这个控件还是非常重要的.所以把使用心得总结下,废话不多说,直接上代码. public class MainActivity extends Activ ...

  3. 不得不吐槽的Android PopupWindow的几个痛点(实现带箭头的上下文菜单遇到的坑)

    说到PopupWindow,我个人感觉是又爱又恨,没有深入使用之前总觉得这个东西应该很简单,很好用,但是真正使用PopupWindow实现一些效果的时候总会遇到一些问题,但是即便是人家的api有问题, ...

  4. 仿QQ空间根据位置弹出PopupWindow显示更多操作效果

    我们打开QQ空间的时候有个箭头按钮点击之后弹出PopupWindow会根据位置的变化显示在箭头的上方还是下方,比普通的PopupWindow弹在屏幕中间显示好看的多. 先看QQ空间效果图:       ...

  5. 自定义PopupWindow

    PopupWindow,一个弹出窗口控件,可以用来显示任意View,而且会浮动在当前activity的顶部 自定义PopupWindow. 1.extends PopupWindow 2.构造方法中可 ...

  6. PopupWindow 使用

    昨天马失前蹄,为了做一个小键盘,耽误了两个小时,记录一下心路历程 1.关于需求与选择 需求: 点击一个按钮,弹出一个小键盘(类似于输入法键盘) 选择: (1)方案一:KeyboardView 这是百度 ...

  7. popupwindow的基本使用以及基本动画效果

    1.创建一个popupwindow view的布局文件自己写一个就好了,这里就不说了 View view= LayoutInflater.from(context).inflate(R.layout. ...

  8. Android -- PopupWindow(其中嵌套ListView 可以被点击)

    1. 效果图

  9. Android开发学习之路-PopupWindow和仿QQ左滑删除

    这周作业,要做一个类似QQ的左滑删除效果的ListView,因为不想给每个item都放一个按钮,所以决定用PopupWindow,这里记录一下 先放一下效果图: 先说明一下这里面的问题: ①没有做到像 ...

  10. android标题栏上面弹出提示框(二) PopupWindow实现,带动画效果

    需求:上次用TextView写了一个从标题栏下面弹出的提示框.android标题栏下面弹出提示框(一) TextView实现,带动画效果,  总在找事情做的产品经理又提出了奇葩的需求.之前在通知栏显示 ...

随机推荐

  1. 存量数据处理结果查询.txt

    请求报文:<?xml version="1.0" encoding="UTF-8"?><PDL><PDL-Head>< ...

  2. 使用python获得git中分支存成list

    通过这个搜集git工程下的branch信息例子,来说明一下python和终端的信息交互,和字符串的简单处理.代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

  3. True or False

    任何对象都可以被测试真值.用于if或while条件中或作为下面的布尔操作的操作数.以下值被视为假: None False 任何数值类型的零,例如,0.0.0.0j . 任何空序列,例如,". ...

  4. C# try catch finally 执行

    try { //dosomething eg: int a = 1; int b = 2; int c = a + b; if(c>2) { return; } } catch(Exceptio ...

  5. ags js下载地址

    https://developers.arcgis.com/en/downloads/ 备用

  6. jQuery(一)delegate() 方法

    定义和用法 delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数. 使用 delegate() 方法的事件处理程序适用于当前或未来 ...

  7. codis3.1集群搭建

    Codis31搭建 codis 3.1 安装搭建 一.基本信息 1. 服务器基本信息 ip地址 安装服务 172.16.200.71 zk1.codis-dashboard.codis-fe.codi ...

  8. System.Data.SQLite数据库简介

    SQLite介绍 在介绍System.Data.SQLite之前需要介绍一下SQLite,SQLite是一个类似于Access的单机版数据库管理系统,它将所有数据库的定义(包括定义.表.索引和数据本身 ...

  9. CSS去除链接虚线(兼容IE6、IE7)

    在css里加入以下代码: a{    hide-focus: expression( this.hideFocus=true );    outline: none;}

  10. [ACM] hdu 1181 变形课

    变形课 Problem Description 呃......变形课上Harry碰到了一点小麻烦,由于他并不像Hermione那样可以记住全部的咒语而任意的将一个棒球变成刺猬什么的,可是他发现了变形咒 ...