編輯:關於 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 了。
以上就是本文的全部內容,希望對大家的學習有所幫助。
仿探探卡片滑動效果:RecyclerView + ItemTouchHelper 實踐
探探式的卡片滑動效果,核心在於「卡片層疊、滑動手勢與回收重用」。如果直接建立大量 View,很容易造成效能問題;因此,實作時通常會以 RecyclerView 搭配自定義
Android 屬性動畫(下):Evaluator、Keyframe、布局動畫與轉場動畫
前言 上一篇我們把屬性動畫的實作骨幹講完了:怎麼寫一個動畫、怎麼在沒有現成屬性的情況下自行補上屬性,以及怎麼用 ValueAnimator 驅動動畫。本篇接著把剩下的幾
SwipeRefreshLayout 下拉刷新控件源碼解析
SwipeRefreshLayout 是 Android 官方提供的下拉刷新控件,使用簡單、界面美觀。本文直接進入正題,梳理它的運作流程。 整體原理 這類下拉刷新控件
Android 自定義控件:繼承 ProgressBar 打造多段視頻進度條
一、需求背景 前陣子做視頻相關的功能,需求是播放本地視頻。當時想著怎麼簡單怎麼來,直接用了 VideoView——後來發現它的靈活性實在有限,想換個樣式都得繞一大圈。 真