編輯:關於Android編程
PopupWindow使用
PopupWindow這個類用來實現一個彈出框,可以使用任意布局的View作為其內容,這個彈出框是懸浮在當前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) {
// 一個自定義的布局,作為顯示的內容
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了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
Android四大組件之一——Activity知識匯總
一. Activity的定義及作用官方定義:Activity是Android應用程序提供交互界面的一個重要組件。也是Android最重要的組件之一Activity是業務類
設計模式MVC for Android
算來學習Android開發已有2年的歷史了,在這2年的學習當中,基本掌握了Android的基礎知識。越到後面的學習越感覺困難,一來是自認為android沒啥可學的了(自認
酷狗音樂歌詞怎麼解鎖
有時候我們在聽歌的時候,鼠標點擊桌面,而歌詞又想顯示出來,為了不擋住桌面的運作,通常都把歌詞鎖住,那麼酷狗音樂歌詞怎麼上鎖解鎖呢?請看教程第一步,鼠標移到歌
Android混淆心得
最近在做Android應用的混淆,踩了一些坑,這裡記錄分享下個人的心得。混淆介紹首先先簡單說一下什麼是混淆和混淆的作用,其實這個搜索下可以找到一堆官方的說法等等,這裡簡單