PopupWindow的基本使用

寫在前面的話

PopupWindow 對于我們來說已經是再熟悉不過了,但是今天在涉及到一個需要用到 PopupWindow 的功能的時候,在顯示PopupWindow 位置的時候卻出問題了,干開發時間也不短了,以前在 用到 PopupWindow的時候,總是馬虎的應付過,雖然功能是實現了,但是對于PopupWindow的一些基本使用還是模模糊糊,感到很難堪啊,再加上以前封裝的關于PopupWindow位置顯示的類今天在使用的時候竟然出現了些問題,實在不得不把它拿出來重新弄弄,也算是做個復習吧。

本篇文章要講解的重點是

  • PopupWindow 基于 view 的位置顯示,如顯示在view左邊,右邊,上邊,下邊
  • PopupWindow 彈出動畫的方式,從上到下,等等。
    整理的原因是避免每次要用到的時候,都在網上翻來覆去的找。

ok,下面就開始正式講解了。

第一步,為了方便新建Popuwindow,我自建了一個BasePopupWindow,里面封裝了PopupWindow 基于 view 位置顯示的方法,下面看看 BasePopupWindow.java 代碼吧:
/***
 * PopupWindow基類
 * 
 * @author pei
 * @version 1.0
 * @cretae 2016-7-21
 * @注:若要popwindow點擊外部消失,則設置 this.setFocusable(true)
 *     若要popwindow點擊外部不消失,不做setFocusable設置,也不要設置成this.setFocusable(false)
 * 
 */
public abstract class BasePopupWindow extends PopupWindow {

    protected View mLayoutView;
    protected int mLayoutId;
    protected Context mContext;
    protected int mWidth;
    protected int mHeight;

    public BasePopupWindow(int width, int height, int layoutId, Context context) {
        this.mWidth = width;
        this.mHeight = height;
        this.mLayoutId = layoutId;
        this.mContext = context;
        mLayoutView = LayoutInflater.from(context).inflate(mLayoutId, null);
        setWindow();
    }

    /** PopupWindow基本設置 **/
    protected void setWindow() {
        this.setContentView(mLayoutView);
        this.setWidth(mWidth);
        this.setHeight(mHeight);
        // this.setFocusable(true);// 可點擊
        // 實例化一個ColorDrawable顏色為半透明(半透明遮罩顏色代碼#66000000)
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        this.setBackgroundDrawable(dw);
    }

    /** PopupWindow背景設置 **/
    protected void setBackground(int color) {
        // 實例化一個ColorDrawable顏色為半透明
        ColorDrawable dw = new ColorDrawable(color);
        this.setBackgroundDrawable(dw);
    }

    protected abstract void initView();
    protected abstract void initData();
    protected abstract void setListener();

    /** PopupWindow點擊間隙處理,根據實際情況重寫 **/
    protected void onTouchdimiss() {
        // mMenuView添加OnTouchListener監聽判斷獲取觸屏位置如果在選擇框外面則銷毀彈出框
        mLayoutView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
//              int height = mLayoutView.getTop();
//              int y = (int) event.getY();
//              if (event.getAction() == MotionEvent.ACTION_UP) {
//                  if (y < height) {
//                      dismiss();
//                  }
//              }
                return false;
            }
        });
    }

    /**
     * 顯示在控件正上方
     * 
     * @param view
     *            依賴的控件
     * @param marginDp
     *            設置的間距(直接寫數字即可,已經做過dp2px轉換)
     */
    public void showAtLocationTop(View view, float marginDp) {
        mLayoutView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popupWidth = mLayoutView.getMeasuredWidth();
        int popupHeight = mLayoutView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        showAtLocation(view, Gravity.NO_GRAVITY, (location[0] + view.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight - dp2px(marginDp));
        update();
    }

    /**
     * 顯示在控件正下方
     * 
     * @param view
     *            依賴的控件
     * @param marginDp
     *            設置的間距(直接寫數字即可,已經做過dp2px轉換)
     */
    public void showAtLocationGravityBottom(View view, float marginDp) {
        mLayoutView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popupWidth = mLayoutView.getMeasuredWidth();
        int popupHeight = mLayoutView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        showAtLocation(view, Gravity.NO_GRAVITY, (location[0]+view.getWidth()/2)-popupWidth/2,
                location[1]+view.getHeight()+dp2px(marginDp));
        update();
    }

    /**顯示在控件下方
     *
     * @param view 依賴的控件
     * @param marginDp  設置的間距(直接寫數字即可,已經做過dp2px轉換)
     */
    public void showAtLocationBottom(View view, float marginDp){
        showAsDropDown(view, 0, dp2px(marginDp));
        update();
    }


    /**
     * 顯示在控件左方
     * 
     * @param view
     *            依賴的控件
     * @param marginDp
     *            設置的間距(直接寫數字即可,已經做過dp2px轉換)
     */
    public void showAtLocationLeft(View view, float marginDp) {
        mLayoutView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popupWidth = mLayoutView.getMeasuredWidth();
        int popupHeight = mLayoutView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        showAtLocation(view, Gravity.NO_GRAVITY, location[0] - popupWidth - dp2px(marginDp), (location[1] + view.getHeight() / 2) - popupHeight / 2);
        update();
    }

    /**
     * 顯示在控件右方
     * 
     * @param view
     *            依賴的控件
     * @param marginDp
     *            設置的間距(直接寫數字即可,已經做過dp2px轉換)
     */
    public void showAtLocationRight(View view, float marginDp) {
        mLayoutView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int popupWidth = mLayoutView.getMeasuredWidth();
        int popupHeight = mLayoutView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        showAtLocation(view, Gravity.NO_GRAVITY, location[0] + view.getWidth() + dp2px(marginDp), (location[1] + view.getHeight() / 2) - popupHeight / 2);
        update();
    }

    /** dp轉px **/
    private int dp2px(float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, mContext.getResources().getDisplayMetrics());
    }

    /** 通過id獲得view **/
    @SuppressWarnings("unchecked")
    protected <T extends View> T getView(int viewId) {
        View view = null;
        if (mLayoutView == null) {
            mLayoutView = LayoutInflater.from(mContext).inflate(mLayoutId, null);
        }
        view = mLayoutView.findViewById(viewId);
        return (T) view;
    }
}
第二步,寫一個簡單的TestPop繼承BasePopuWindow,用于做測試,TestPop 代碼如下:
/**
 * Instruction:用于測試的popuwindow
 * <p>
 * Author:pei
 * Date: 2017/6/28
 * Description:
 */


public class TestPop extends BasePopupWindow{

    public TestPop(Context context) {
        super(ScreenUtil.dp2px(100,context), ScreenUtil.dp2px(50,context), R.layout.pop_order, context);

        initView();
        initData();
        setListener();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        setFocusable(true);
        setAnimationStyle(R.style.popuwindow_up_style);//popuwindow顯示隱藏的動畫

    }

    @Override
    protected void setListener(){

    }
}

需要說明的是,為了方便測試,我TestPop設的固定大小

width=ScreenUtil.dp2px(100,context);
hight=ScreenUtil.dp2px(50,context);

TestPop 涉及到的popuwindow的布局 layout.pop_order.xml 如下:

<?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="match_parent"
    android:background="@color/color_c0c0c0">

</LinearLayout>
第三步,mainactivity中的測試代碼很簡單,就是寫了一個點擊事件用來控制TestPop的顯示和消失。

下面,讓我們來看看,Mainactivity中的點擊時間是怎么控制TestPop
的:

    @Override
    public void onClick(View v) {
         switch (v.getId()) {
            case R.id.tv_spanner:
                TestPop testPop = new TestPop(mContext);
                if (testPop.isShowing()) {
                    testPop.dismiss();
                } else {
                    testPop.showAtLocationBottom(mTvSpanner, 5);
                }
                break;
            default:
                break;
        }
    }

下面,讓我們來看看,popwi固定顯示在某個view方位的具體方法:

//顯示在控件正上方
showAtLocationTop(View view, float marginDp)
//顯示在控件正下方(中線對齊)
showAtLocationGravityBottom(View view, float marginDp)
//顯示在控件下方(左邊對齊)
showAtLocationBottom(View view, float marginDp)
//顯示在控件左方
showAtLocationLeft(View view, float marginDp)
//顯示在控件右方
showAtLocationRight(View view, float marginDp)
之前講到popuwindow的位置顯示問題,下面講講popuwindow動畫彈出的問題
  • popuwindow從屏幕上面進入
    在 res/anim 文件夾下建xml文件(anim不存在的話自己創建)
    popu_up_in.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<!-- 從屏幕上面進入 -->
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromYDelta="-100%p"
        android:toYDelta="0" />

    <alpha
        android:duration="500"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

popu_up_out.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- 從屏幕上面退出 -->
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="500"
        android:fromYDelta="0"
        android:toYDelta="-100%p" />

    <alpha
        android:duration="500"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>

新建style主題,用于popuwindow引用

   <style name="popuwindow_up_style">
        <item name="android:windowEnterAnimation">@anim/popu_up_in</item>
        <item name="android:windowExitAnimation">@anim/popu_up_out</item>
    </style>

在popuwindow中的引用如下:

setAnimationStyle(R.style.popuwindow_up_style);//popuwindow顯示隱藏的動畫

效果圖如下:

up.gif
  • popuwindow 的left_top效果
    在 res/anim 文件夾下建xml文件(anim不存在的話自己創建)
    popu_left_top_in.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

popu_left_top_out.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toXScale="0.0"
        android:toYScale="0.0" />
</set>

新建style主題,用于popuwindow引用

<style name="popuwindow_left_top_style">
        <item name="android:windowEnterAnimation">@anim/popu_left_top_in</item>
        <item name="android:windowExitAnimation">@anim/popu_left_top_out</item>
    </style>

在popuwindow中的引用如下:

setAnimationStyle(R.style.popuwindow_left_top_style);//popuwindow顯示隱藏的動畫

效果圖如下:

left_top.gif
  • popuwindow 的right_top效果
    在 res/anim 文件夾下建xml文件(anim不存在的話自己創建)
    popu_right_top_in.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="100%"
        android:pivotY="0%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

popu_right_top_out.xml 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="100%"
        android:pivotY="0%"
        android:toXScale="0.0"
        android:toYScale="0.0" />
</set>

新建style主題,用于popuwindow引用

<style name="popuwindow_right_top_style">
        <item name="android:windowEnterAnimation">@anim/popu_right_top_in</item>
        <item name="android:windowExitAnimation">@anim/popu_right_top_out</item>
    </style>

在popuwindow中的引用如下:

setAnimationStyle(R.style.popuwindow_right_top_style);//popuwindow顯示隱藏的動畫

效果圖如下:

right_top.gif
  • popuwindow 的middle_style效果
    在 res/anim 文件夾下建xml文件(anim不存在的話自己創建)
    popu_middle_in.xml 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="0.0"
        android:fromYScale="0.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="0%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

popu_middle_out.xml 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <scale
        android:duration="500"
        android:fillAfter="false"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="0%"
        android:toXScale="0.0"
        android:toYScale="0.0" />
</set>

新建style主題,用于popuwindow引用

<style name="popuwindow_middle_style">
        <item name="android:windowEnterAnimation">@anim/popu_middle_in</item>
        <item name="android:windowExitAnimation">@anim/popu_middle_out</item>
    </style>

在popuwindow中的引用如下:

setAnimationStyle(R.style.popuwindow_middle_style);//popuwindow顯示隱藏的動畫

效果圖如下:

middle_style.gif

ok,關于popuwindow就寫到這里了,謝謝誒。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容