Android PopupWindow用法解析
PopupWindow使用
PopupWindow這個(gè)類用來實(shí)現(xiàn)一個(gè)彈出框,可以使用任意布局的View作為其內(nèi)容,這個(gè)彈出框是懸浮在當(dāng)前activity之上的。
PopupWindow使用Demo
這個(gè)類的使用,不再過多解釋,直接上代碼吧。
比如彈出框的布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://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的布局中只有一個(gè)按鈕,按下后會(huì)彈出框,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) { // 一個(gè)自定義的布局,作為顯示的內(nèi)容 View contentView = LayoutInflater.from(mContext).inflate( R.layout.pop_window, null); // 設(shè)置按鈕的點(diǎn)擊事件 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不被調(diào)用,這樣點(diǎn)擊外部區(qū)域無法dismiss } }); // 如果不設(shè)置PopupWindow的背景,無論是點(diǎn)擊外部區(qū)域還是Back鍵都無法dismiss彈框 // 我覺得這里是API的一個(gè)bug popupWindow.setBackgroundDrawable(getResources().getDrawable( R.drawable.selectmenu_bg_downward)); // 設(shè)置好參數(shù)之后再show popupWindow.showAsDropDown(view); } }
彈出框的布局中有一個(gè)TextView和一個(gè)Button,Button點(diǎn)擊后顯示Toast,如圖:
第一次實(shí)現(xiàn)的時(shí)候遇到了問題,就是彈出框不會(huì)在按下Back鍵的時(shí)候消失,點(diǎn)擊彈框外區(qū)域也沒有正常消失,搜索了一下,都說只要設(shè)置背景就好了。
然后我就找了個(gè)圖片,果然彈框能正常dismiss了(見注釋)。
PopupWindow源碼分析
為了解答一下上面的問題,看看源碼(最新API Level 19,Android 4.4.2)。
1.顯示方法
顯示提供了兩種形式:
showAtLocation()顯示在指定位置,有兩個(gè)方法重載:
public void showAtLocation(View parent, int gravity, int x, int y) public void showAtLocation(IBinder token, int gravity, int x, int y)
showAsDropDown()顯示在一個(gè)參照物View的周圍,有三個(gè)方法重載:
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參數(shù)的方法是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事件的影響
如果有背景,則會(huì)在contentView外面包一層PopupViewContainer之后作為mPopupView,如果沒有背景,則直接用contentView作為mPopupView。
而這個(gè)PopupViewContainer是一個(gè)內(nèi)部私有類,它繼承了FrameLayout,在其中重寫了Key和Touch事件的分發(fā)處理:
@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事件的處理,所以如果沒有包這個(gè)外層容器類,點(diǎn)擊Back鍵或者外部區(qū)域是不會(huì)導(dǎo)致彈框消失的。
補(bǔ)充Case: 彈窗不消失,但是事件向下傳遞
如上所述:
設(shè)置了PopupWindow的background,點(diǎn)擊Back鍵或者點(diǎn)擊彈窗的外部區(qū)域,彈窗就會(huì)dismiss.
相反,如果不設(shè)置PopupWindow的background,那么點(diǎn)擊back鍵和點(diǎn)擊彈窗的外部區(qū)域,彈窗是不會(huì)消失的.
那么,如果我想要一個(gè)效果,點(diǎn)擊外部區(qū)域,彈窗不消失,但是點(diǎn)擊事件會(huì)向下面的activity傳遞,比如下面是一個(gè)WebView,我想點(diǎn)擊里面的鏈接等.
研究了半天,說是要給Window設(shè)置一個(gè)Flag,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
看了源碼,這個(gè)Flag的設(shè)置與否是由一個(gè)叫mNotTouchModal的字段控制,但是設(shè)置該字段的set方法被標(biāo)記為@hide。
所以要通過反射的方法調(diào)用:
/** * 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了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android中PopupWindow使用方法詳解
- Android實(shí)現(xiàn)滑動(dòng)刪除操作(PopupWindow)
- Android編程實(shí)現(xiàn)popupwindow彈出后屏幕背景變成半透明效果
- Android Animation實(shí)戰(zhàn)之屏幕底部彈出PopupWindow
- Android PopupWindow 點(diǎn)擊外面取消實(shí)現(xiàn)代碼
- Android中PopupWindow響應(yīng)返回鍵并關(guān)閉的2種方法
- Android入門之PopupWindow用法實(shí)例解析
- android教程之使用popupwindow創(chuàng)建菜單示例
- Android之用PopupWindow實(shí)現(xiàn)彈出菜單的方法詳解
- android popwindow實(shí)現(xiàn)左側(cè)彈出菜單層及PopupWindow主要方法介紹
相關(guān)文章
通過OpenGL ES混合模式縮放視頻緩沖區(qū)來適應(yīng)顯示尺寸
當(dāng)開發(fā)基于軟件模式的游戲時(shí),通過縮放視頻緩沖區(qū)來適應(yīng)顯示尺寸是最棘手的問題之一;作為開發(fā)人員,我們必須嘗試在性能與顯示質(zhì)量之間找到最佳平衡點(diǎn)2012-12-12Android 通過API獲取數(shù)據(jù)庫中的圖片文件方式
這篇文章主要介紹了Android 通過API獲取數(shù)據(jù)庫中的圖片文件方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android Flutter實(shí)現(xiàn)GIF動(dòng)畫效果的方法詳解
如果我們想對某個(gè)組件實(shí)現(xiàn)一組動(dòng)效應(yīng)該怎么辦呢?本文將利用Android Flutter實(shí)現(xiàn)GIF動(dòng)畫效果,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-06-06clipse項(xiàng)目遷移到android studio的方法(圖文最新版)
這篇文章主要介紹了clipse項(xiàng)目遷移到android studio(圖文最新版),需要的朋友可以參考下2015-10-10