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

