PopupWindow使用

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

 

Reference

  http://developer.android.com/reference/android/widget/PopupWindow.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章