android之PopupWindow

内部类:

interfacePopupWindow.OnDismissListenerListener that is called when this popup window is dismissed. 
xml attributes:

Attribute Name Related Method Description
android:popupBackgroundsetBackgroundDrawable(Drawable)The background to use for the popup window. 
android:popupElevationsetElevation(float)Window elevation to use for the popup window.                           

常量:

intINPUT_METHOD_FROM_FOCUSABLEMode for setInputMethodMode(int): the requirements for the input method should be based on the focusability of the popup.                          
intINPUT_METHOD_NEEDEDMode for setInputMethodMode(int): this popup always needs to work with an input method, regardless of whether it is focusable.                          
intINPUT_METHOD_NOT_NEEDEDMode for setInputMethodMode(int): this popup never needs to work with an input method, regardless of whether it is focusable.                          

PopupWindow( Context context)

Create a new empty, non focusable popup window of dimension (0,0).

PopupWindow( Context context, AttributeSet attrs)

Create a new empty, non focusable popup window of dimension (0,0).

PopupWindow( Context context, AttributeSet attrs, int defStyleAttr)

Create a new empty, non focusable popup window of dimension (0,0).

PopupWindow( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Create a new, empty, non focusable popup window of dimension (0,0).

PopupWindow()

Create a new empty, non focusable popup window of dimension (0,0).

PopupWindow( View contentView)

Create a new non focusable popup window which can display the contentView.

PopupWindow(int width, int height)

Create a new empty, non focusable popup window.

PopupWindow( View contentView, int width, int height)

Create a new non focusable popup window which can display the contentView.

PopupWindow( View contentView, int width, int height, boolean focusable)

Create a new popup window which can display the contentView.                          


void dismiss()
Disposes of the popup window.
int getAnimationStyle()

Return the animation style to use the popup appears and disappears

Drawable getBackground()
Return the drawable used as the popup window's background.
View getContentView()

Return the view used as the content of the popup window.

float getElevation()
int getHeight()
Returns the popup's height MeasureSpec.
int getInputMethodMode()
Return the current value in setInputMethodMode(int).
int getMaxAvailableHeight( View anchor)
Returns the maximum height that is available for the popup to be completely shown.
int getMaxAvailableHeight( View anchor, int yOffset)
Returns the maximum height that is available for the popup to be completely shown.
boolean getOverlapAnchor()
Returns whether the popup window should overlap its anchor view when displayed as a drop-down.
int getSoftInputMode()
Returns the current value in setSoftInputMode(int).
int getWidth()
Returns the popup's width MeasureSpec.
int getWindowLayoutType()
Returns the layout type for this window.
boolean isAboveAnchor()
Indicates whether the popup is showing above (the y coordinate of the popup's bottom is less than the y coordinate of the anchor) or below the anchor view (the y coordinate of the popup is greater than y coordinate of the anchor's bottom).
boolean isAttachedInDecor()

Indicates whether the popup window will be attached in the decor frame of its parent window.

boolean isClippingEnabled()

Indicates whether clipping of the popup window is enabled.

boolean isFocusable()

Indicate whether the popup window can grab the focus.

boolean isOutsideTouchable()

Indicates whether the popup window will be informed of touch events outside of its window.

boolean isShowing()

Indicate whether this popup window is showing on screen.

boolean isSplitTouchEnabled()

Indicates whether the popup window supports splitting touches.

boolean isTouchable()

Indicates whether the popup window receives touch events.

void setAnimationStyle(int animationStyle)

Change the animation style resource for this popup.

void setAttachedInDecor(boolean enabled)

This will attach the popup window to the decor frame of the parent window to avoid overlaping with screen decorations like the navigation bar.

void setBackgroundDrawable( Drawable background)
Specifies the background drawable for this popup window.
void setClippingEnabled(boolean enabled)

Allows the popup window to extend beyond the bounds of the screen.

void setContentView( View contentView)

Change the popup's content.

void setElevation(float elevation)
Specifies the elevation for this popup window.
void setEnterTransition( Transition enterTransition)
void setExitTransition( Transition exitTransition)
void setFocusable(boolean focusable)

Changes the focusability of the popup window.

void setHeight(int height)
Sets the popup's height MeasureSpec.
void setIgnoreCheekPress()
Set the flag on popup to ignore cheek press events; by default this flag is set to false which means the popup will not ignore cheek press dispatch events.
void setInputMethodMode(int mode)
Control how the popup operates with an input method: one of INPUT_METHOD_FROM_FOCUSABLE, INPUT_METHOD_NEEDED, or INPUT_METHOD_NOT_NEEDED.
void setOnDismissListener( PopupWindow.OnDismissListener onDismissListener)
Sets the listener to be called when the window is dismissed.
void setOutsideTouchable(boolean touchable)

Controls whether the pop-up will be informed of touch events outside of its window.

void setOverlapAnchor(boolean overlapAnchor)
Sets whether the popup window should overlap its anchor view when displayed as a drop-down.
void setSoftInputMode(int mode)
Sets the operating mode for the soft input area.
void setSplitTouchEnabled(boolean enabled)

Allows the popup window to split touches across other windows that also support split touch.

void setTouchInterceptor( View.OnTouchListener l)
Set a callback for all touch events being dispatched to the popup window.
void setTouchable(boolean touchable)

Changes the touchability of the popup window.

void setWidth(int width)
Sets the popup's width MeasureSpec.
void setWindowLayoutMode(int widthSpec, int heightSpec)
This method was deprecated in API level 23. Use setWidth(int) andsetHeight(int).
void setWindowLayoutType(int layoutType)
Set the layout type for this window.
void showAsDropDown( View anchor, int xoff, int yoff, int gravity)
Displays the content view in a popup window anchored to the corner of another view.
void showAsDropDown( View anchor, int xoff, int yoff)
Display the content view in a popup window anchored to the bottom-left corner of the anchor view offset by the specified x and y coordinates.
void showAsDropDown( View anchor)
Display the content view in a popup window anchored to the bottom-left corner of the anchor view.
void showAtLocation( View parent, int gravity, int x, int y)

Display the content view in a popup window at the specified location.

void update( View anchor, int width, int height)
Updates the position and the dimension of the popup window.
void update(int x, int y, int width, int height)
Updates the position and the dimension of the popup window.
void update( View anchor, int xoff, int yoff, int width, int height)
Updates the position and the dimension of the popup window.
void update()
Updates the state of the popup window, if it is currently being displayed, from the currently set state.
void update(int x, int y, int width, int height, boolean force)
Updates the position and the dimension of the popup window.
void update(int width, int height)
Updates the dimension of the popup window.                          

2、demo

package com.james.popupwindow;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btnBelowWindow;
    private Button btnAboveWindow;
    private Button btnPopupMenu;
    private Button btnPopupListView;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow2;
    private PopupWindow popupWindow3;
    private PopupWindow popupWindow4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBelowWindow = (Button) findViewById(R.id.id_btn_below_window);
        btnAboveWindow = (Button) findViewById(R.id.id_btn_above_window);
        btnPopupMenu = (Button) findViewById(R.id.id_btn_popup_menu);
        btnPopupListView = (Button) findViewById(R.id.id_btn_pop_list_view);
        btnBelowWindow.setOnClickListener(this);
        btnAboveWindow.setOnClickListener(this);
        btnPopupMenu.setOnClickListener(this);
        btnPopupListView.setOnClickListener(this);
        View view1 = getLayoutInflater().inflate(R.layout.item_popup,null);
        popupWindow = new PopupWindow();
        popupWindow.setContentView(view1);
        int width = LinearLayout.LayoutParams.WRAP_CONTENT;
        int height = LinearLayout.LayoutParams.WRAP_CONTENT;
        popupWindow.setWidth(width);
        popupWindow.setHeight(height);
        //点击空白,消失
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap) null));

        View topView = getLayoutInflater().inflate(R.layout.item_popup2,null);
        popupWindow2 = new PopupWindow();
        popupWindow2.setContentView(topView);
        popupWindow2.setWidth(width);
        popupWindow2.setHeight(height);
        popupWindow2.setTouchable(true);
        popupWindow2.setOutsideTouchable(true);
        popupWindow2.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap)null));

        View menuView = getLayoutInflater().inflate(R.layout.item_popup_menu,null);
        popupWindow3 = new PopupWindow();
        popupWindow3.setContentView(menuView);
        popupWindow3.setWidth(width);
        popupWindow3.setHeight(height);
        popupWindow3.setTouchable(true);
        popupWindow3.setOutsideTouchable(true);
        popupWindow3.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap)null));

        List<String> stringList = new ArrayList<>();
        for(int i=0;i<30;i++){
            stringList.add("item:"+i);
        }
        View listView = getLayoutInflater().inflate(R.layout.item_popup_list,null);
        ListView listView1 = (ListView) listView.findViewById(R.id.id_list_view);
        ListViewAdapter listViewAdapter = new ListViewAdapter(stringList);
        listView1.setAdapter(listViewAdapter);
        popupWindow4 = new PopupWindow();
        popupWindow4.setContentView(listView);
        popupWindow4.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow4.setHeight(height);
        popupWindow4.setTouchable(true);
        popupWindow4.setOutsideTouchable(true);
        popupWindow4.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap)null));


        popupWindow4.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(MainActivity.this, 1f);
            }
        });

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this,"--i:"+i,Toast.LENGTH_SHORT).show();
                if(popupWindow4.isShowing()){
                    popupWindow4.dismiss();
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.id_btn_below_window:
                if(popupWindow.isShowing()){
                    popupWindow.dismiss();
                }else {
                    popupWindow.showAsDropDown(view);
                }
                break;

            case R.id.id_btn_above_window:
                if(popupWindow2.isShowing()){
                    popupWindow2.dismiss();
                }else {
                    int height = getResources().getDrawable(R.mipmap.pop_bg2).getIntrinsicHeight();
                    int btnHeight = view.getHeight();
                    popupWindow2.showAsDropDown(view,0,-(height+ btnHeight));
                }
                break;
            case R.id.id_btn_popup_menu:
                if(popupWindow3.isShowing()){
                    popupWindow3.dismiss();
                }else {
                    popupWindow3.showAsDropDown(view);
                }
                break;
            case R.id.id_btn_pop_list_view:
                if(popupWindow4.isShowing()){
                    popupWindow4.dismiss();
                }else {
                    ColorDrawable dw = new ColorDrawable(0x00000000);
                    //设置SelectPicPopupWindow弹出窗体的背景
                    popupWindow4.setBackgroundDrawable(dw);
                    backgroundAlpha(this,0.5f);//0.0-1.0

                    popupWindow4.showAsDropDown(view);
                }
                break;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha)
    {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

}
package com.james.popupwindow;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Administrator on 2016/12/4 0004.
 */

public class ListViewAdapter extends BaseAdapter {
    private List<String> stringList;
    public ListViewAdapter(List<String> stringList) {
        this.stringList = stringList;
    }

    @Override
    public int getCount() {
        return stringList.size();
    }

    @Override
    public Object getItem(int i) {
        return stringList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if(view == null){
            view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_text_view,viewGroup,false);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.itemName.setText(stringList.get(i));

        return view;
    }
    private class ViewHolder {
        TextView itemName;
        public ViewHolder(View view) {
            itemName = (TextView) view.findViewById(R.id.id_tv_textview);

        }
    }
}

activity_main.xm:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="com.james.popupwindow.MainActivity">
    <Button
        android:id="@+id/id_btn_below_window"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 下方弹窗"/>
    <Button
        android:id="@+id/id_btn_above_window"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 上方弹窗"/>
    <Button
        android:id="@+id/id_btn_popup_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="pop 菜单弹窗"/>
    <Button
        android:id="@+id/id_btn_pop_list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="pop ListView列表"/>
</LinearLayout>

item_popup.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@mipmap/pop_bg"
    android:paddingTop="25dp"
    android:paddingLeft="20dp"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1、this is tip 1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2、this is tip 2"/>
</LinearLayout>
item_popup2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@mipmap/pop_bg2"
    android:paddingTop="20dp"
    android:paddingLeft="20dp"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1、this is tip 1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2、this is tip 2"/>
</LinearLayout>
item_popup_list.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:orientation="vertical">
    <ListView
        android:id="@+id/id_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
item_popup_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/menu_pop_bg"
    android:padding="10dp"
    >
    <LinearLayout
        android:id="@+id/menu1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        >
        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:src="@mipmap/ic_icon1"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:text="Item 菜单1"
            android:layout_marginLeft="10dp"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/menu2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="10dp"
        >
        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:src="@mipmap/ic_icon2"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:text="Item 菜单2"
            android:layout_marginLeft="10dp"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/menu3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="10dp"
        >
        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:src="@mipmap/icon_item3"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:text="Item 菜单3"
            android:layout_marginLeft="10dp"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/menu4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="10dp"
        >
        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:src="@mipmap/ic_icon4"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:text="Item 菜单4"
            android:layout_marginLeft="10dp"
            />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/menu5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_marginTop="10dp"
        >
        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:src="@mipmap/ic_icon5"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:text="Item 菜单5"
            android:layout_marginLeft="10dp"
            />
    </LinearLayout>
</LinearLayout>

item_text_view.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="@android:color/white"
    android:orientation="vertical">

    <TextView
        android:id="@+id/id_tv_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
menu_pop_bg.xml:drawable文件夹下

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <corners android:radius="5dp"/>
    <solid android:color="@android:color/white"/>
    <stroke android:color="@android:color/darker_gray"
        android:width="1px"/>
</shape>

3、高级,封装

package com.example.zhouwei.library;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

/**
 *
 * 自定义PopWindow类,封装了PopWindow的一些常用属性,用Builder模式支持链式调用
 * Created by zhouwei on 16/11/28.
 */

public class CustomPopWindow {
    private Context mContext;
    private int mWidth;
    private int mHeight;
    private boolean mIsFocusable = true;
    private boolean mIsOutside = true;
    private int mResLayoutId = -1;
    private View mContentView;
    private PopupWindow mPopupWindow;
    private int mAnimationStyle = -1;

    private boolean mClippEnable = true;//default is true
    private boolean mIgnoreCheekPress = false;
    private int mInputMode = -1;
    private PopupWindow.OnDismissListener mOnDismissListener;
    private int mSoftInputMode = -1;
    private boolean mTouchable = true;//default is ture
    private View.OnTouchListener mOnTouchListener;
    private CustomPopWindow(Context context){
        mContext = context;
    }

    public int getWidth() {
        return mWidth;
    }

    public int getHeight() {
        return mHeight;
    }

    /**
     *
     * @param anchor
     * @param xOff
     * @param yOff
     * @return
     */
    public CustomPopWindow showAsDropDown(View anchor, int xOff, int yOff){
        if(mPopupWindow!=null){
            mPopupWindow.showAsDropDown(anchor,xOff,yOff);
        }
        return this;
    }

    public CustomPopWindow showAsDropDown(View anchor){
        if(mPopupWindow!=null){
            mPopupWindow.showAsDropDown(anchor);
        }
        return this;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public CustomPopWindow showAsDropDown(View anchor, int xOff, int yOff, int gravity){
        if(mPopupWindow!=null){
            mPopupWindow.showAsDropDown(anchor,xOff,yOff,gravity);
        }
        return this;
    }


    /**
     * 相对于父控件的位置(通过设置Gravity.CENTER,下方Gravity.BOTTOM等 ),可以设置具体位置坐标
     * @param parent 父控件
     * @param gravity
     * @param x the popup's x location offset
     * @param y the popup's y location offset
     * @return
     */
    public CustomPopWindow showAtLocation(View parent, int gravity, int x, int y){
        if(mPopupWindow!=null){
            mPopupWindow.showAtLocation(parent,gravity,x,y);
        }
        return this;
    }

    /**
     * 添加一些属性设置
     * @param popupWindow
     */
    private void apply(PopupWindow popupWindow){
        popupWindow.setClippingEnabled(mClippEnable);
        if(mIgnoreCheekPress){
            popupWindow.setIgnoreCheekPress();
        }
        if(mInputMode!=-1){
            popupWindow.setInputMethodMode(mInputMode);
        }
        if(mSoftInputMode!=-1){
            popupWindow.setSoftInputMode(mSoftInputMode);
        }
        if(mOnDismissListener!=null){
            popupWindow.setOnDismissListener(mOnDismissListener);
        }
        if(mOnTouchListener!=null){
            popupWindow.setTouchInterceptor(mOnTouchListener);
        }
        popupWindow.setTouchable(mTouchable);



    }

    private PopupWindow build(){

        if(mContentView == null){
            mContentView = LayoutInflater.from(mContext).inflate(mResLayoutId,null);
        }

        if(mWidth != 0 && mHeight!=0 ){
            mPopupWindow = new PopupWindow(mContentView,mWidth,mHeight);
        }else{
            mPopupWindow = new PopupWindow(mContentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        if(mAnimationStyle!=-1){
            mPopupWindow.setAnimationStyle(mAnimationStyle);
        }

        apply(mPopupWindow);//设置一些属性

        mPopupWindow.setFocusable(mIsFocusable);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindow.setOutsideTouchable(mIsOutside);

        if(mWidth == 0 || mHeight == 0){
            mPopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            //如果外面没有设置宽高的情况下,计算宽高并赋值
            mWidth = mPopupWindow.getContentView().getMeasuredWidth();
            mHeight = mPopupWindow.getContentView().getMeasuredHeight();
        }

        mPopupWindow.update();

        return mPopupWindow;
    }

    /**
     * 关闭popWindow
     */
    public void dissmiss(){
        if(mPopupWindow!=null){
            mPopupWindow.dismiss();
        }
    }


    public static class PopupWindowBuilder{
        private CustomPopWindow mCustomPopWindow;

        public PopupWindowBuilder(Context context){
            mCustomPopWindow = new CustomPopWindow(context);
        }
        public PopupWindowBuilder size(int width,int height){
            mCustomPopWindow.mWidth = width;
            mCustomPopWindow.mHeight = height;
            return this;
        }


        public PopupWindowBuilder setFocusable(boolean focusable){
            mCustomPopWindow.mIsFocusable = focusable;
            return this;
        }



        public PopupWindowBuilder setView(int resLayoutId){
            mCustomPopWindow.mResLayoutId = resLayoutId;
            mCustomPopWindow.mContentView = null;
            return this;
        }

        public PopupWindowBuilder setView(View view){
            mCustomPopWindow.mContentView = view;
            mCustomPopWindow.mResLayoutId = -1;
            return this;
        }

        public PopupWindowBuilder setOutsideTouchable(boolean outsideTouchable){
            mCustomPopWindow.mIsOutside = outsideTouchable;
            return this;
        }

        /**
         * 设置弹窗动画
         * @param animationStyle
         * @return
         */
        public PopupWindowBuilder setAnimationStyle(int animationStyle){
            mCustomPopWindow.mAnimationStyle = animationStyle;
            return this;
        }


        public PopupWindowBuilder setClippingEnable(boolean enable){
            mCustomPopWindow.mClippEnable =enable;
            return this;
        }


        public PopupWindowBuilder setIgnoreCheekPress(boolean ignoreCheekPress){
            mCustomPopWindow.mIgnoreCheekPress = ignoreCheekPress;
            return this;
        }

        public PopupWindowBuilder setInputMethodMode(int mode){
            mCustomPopWindow.mInputMode = mode;
            return this;
        }

        public PopupWindowBuilder setOnDissmissListener(PopupWindow.OnDismissListener onDissmissListener){
            mCustomPopWindow.mOnDismissListener = onDissmissListener;
            return this;
        }


        public PopupWindowBuilder setSoftInputMode(int softInputMode){
            mCustomPopWindow.mSoftInputMode = softInputMode;
            return this;
        }


        public PopupWindowBuilder setTouchable(boolean touchable){
            mCustomPopWindow.mTouchable = touchable;
            return this;
        }

        public PopupWindowBuilder setTouchIntercepter(View.OnTouchListener touchIntercepter){
            mCustomPopWindow.mOnTouchListener = touchIntercepter;
            return this;
        }


        public CustomPopWindow create(){
            //构建PopWindow
            mCustomPopWindow.build();
            return mCustomPopWindow;
        }

    }

}
使用:

package com.example.zhouwei.simple;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhouwei.library.CustomPopWindow;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView mButton1,mButton2,mButton3,mButton4;
    private CustomPopWindow mCustomPopWindow;
    private CustomPopWindow mListPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton1 = (TextView) findViewById(R.id.button1);
        mButton1.setOnClickListener(this);
        mButton2 = (TextView) findViewById(R.id.button2);
        mButton2.setOnClickListener(this);
        mButton3 = (TextView) findViewById(R.id.button3);
        mButton3.setOnClickListener(this);
        mButton4 = (TextView) findViewById(R.id.button4);
        mButton4.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button1:
                showPopBottom();
                break;
            case R.id.button2:
                showPopTop();
                break;
            case R.id.button3:
                showPopMenu();
                break;
            case R.id.button4:
                showPopListView();
                break;
        }
    }

    private void showPopBottom(){
        CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(R.layout.pop_layout1)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .create()
                .showAsDropDown(mButton1,0,10);
    }

    private void showPopTop(){
      CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(this)
              .setView(R.layout.pop_layout2)
              .create();
      popWindow .showAsDropDown(mButton2,0,  - (mButton2.getHeight() + popWindow.getHeight()));
      //popWindow.showAtLocation(mButton1, Gravity.NO_GRAVITY,0,0);
    }

    private void showPopMenu(){
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu,null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow= new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(mButton3,0,20);


    }

    private void showPopListView(){
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_list,null);
        //处理popWindow 显示内容
        handleListView(contentView);
        //创建并显示popWindow
        mListPopWindow= new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAsDropDown(mButton4,0,20);
    }

    private void handleListView(View contentView){
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        MyAdapter adapter = new MyAdapter();
        adapter.setData(mockData());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    private List<String> mockData(){
        List<String> data = new ArrayList<>();
        for (int i=0;i<100;i++){
            data.add("Item:"+i);
        }

        return data;
    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     * @param contentView
     */
    private void handleLogic(View contentView){
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCustomPopWindow!=null){
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()){
                    case R.id.menu1:
                        showContent = "点击 Item菜单1";
                        break;
                    case R.id.menu2:
                        showContent = "点击 Item菜单2";
                        break;
                    case R.id.menu3:
                        showContent = "点击 Item菜单3";
                        break;
                    case R.id.menu4:
                        showContent = "点击 Item菜单4";
                        break;
                    case R.id.menu5:
                        showContent = "点击 Item菜单5" ;
                        break;
                }
                Toast.makeText(MainActivity.this,showContent,Toast.LENGTH_SHORT).show();
            }
        };
        contentView.findViewById(R.id.menu1).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2).setOnClickListener(listener);
        contentView.findViewById(R.id.menu3).setOnClickListener(listener);
        contentView.findViewById(R.id.menu4).setOnClickListener(listener);
        contentView.findViewById(R.id.menu5).setOnClickListener(listener);
    }
}

来源于:https://github.com/pinguo-zhouwei/CustomPopwindow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值