Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android PopupWindow 用法與源碼深入解析

編輯:關於 Android 程式設計

PopupWindow 是什麼
PopupWindow 這個類別用來實作一個彈出框,你可以將任意布局的 View 作為它的內容,而這個彈出框會懸浮顯示在目前的 Activity 之上,非常靈活好用。

PopupWindow 使用示範
這個類別的用法不難,直接看程式碼會更直觀。以下先準備彈出框的布局:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFBBFFBB" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Hello My Window" android:textSize="20sp" /> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Button" android:textSize="20sp" /> </LinearLayout> 

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 方法中可以看到有無背景的差異:

 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; } 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 鍵或點擊外部區域,都不會讓彈出框消失。這正是前面必須設定背景的深層原因。

補充案例:彈窗不消失,但事件向下傳遞
如上所述,設定 background 後,按 Back 鍵或點擊彈窗外部區域就會 dismiss;反而不設定 background,這兩種操作都不會讓彈窗消失。那麼,若想要「點擊外部區域彈窗不消失,但點擊事件會向下傳遞給底層 Activity」的效果該怎麼辦呢?例如底層是一個 WebView,希望點擊其中的連結等。

研究後得知需要為 Window 設定一個 Flag:WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL。查閱源碼發現,這個 Flag 是否設定由一個名為 mNotTouchModal 的欄位控制,但設定該欄位的 set 方法被標記為 @hide,因此必須透過反射來呼叫:

 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 了。

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved