popupWindow 用法总结 控制位置

android中的dialog,以及activiy形式的dialog均是模态对话框, 对话框不消失时,不能对其他页面进行操作,也就是其他页面不能获得焦点。 PopupWindow是 非模态对话框 ,对话框显示的时候,其他界面仍然可以获得焦点,仍然可以进行点击等操作,同时也可以对 对话框 进行点击等操作。 
很好的例子就是输入法,通过查看源码就可以看到,其界面是几个popupwindow组成的。

三个关键设置
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
popupWindow.setBackgroundDrawable(new ColorDrawable());
// setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
popupWindow.setOutsideTouchable(true);
// 设置为true之后,PopupWindow内容区域 才可以响应点击事件
popupWindow.setTouchable(true);

Activity

public class MainActivity extends ListActivity {
    private PopupWindow pop;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] array = { "在指定view的正左下方,无偏移"//
                "相对指定view正左下方,有偏移",//
                "Gravity.NO_GRAVITY:相对屏幕左上角,注意包含状态栏区域",//
                "Gravity.TOP:相对屏幕正上方居中",//
                "pop不会偏移出屏幕,偏移值过大时取临界值",//
                "Gravity.BOTTOM:相对屏幕正下方居中,注意包含虚拟按键区域",//
                "Gravity.BOTTOM:此时yoff为正时表示向上偏移(而非向下偏移)",//
                "出现在View的任意位置"};
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1new ArrayList<String>(Arrays.asList(array))));
        pop = new PopupWindow(this);
        pop.setFocusable(true);//必备设置1
        pop.setBackgroundDrawable(new ColorDrawable(0x00ff0000));//必备设置2
        pop.setOutsideTouchable(true);//setFocusable(true)后这个设置就没用了
        pop.setAnimationStyle(R.style.popAniStyle);//设置动画所对应的style 
    }
    private boolean b;
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        b = !b;
        if (b) pop.setContentView(LayoutInflater.from(this).inflate(R.layout.view1null));
        else pop.setContentView(LayoutInflater.from(this).inflate(R.layout.view2null));
        switch (position) {
        case 0://在指定view的正左下方,无偏移
            pop.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);//必须设置宽和高
            pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            pop.showAsDropDown(v);
            break;
        case 1://相对指定view正左下方的位置,有偏移
            pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
            pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            pop.showAsDropDown(v, 20, 10);
            break;
        case 2://相对于父控件的某个相对位置的偏移,默认的Gravity.NO_GRAVITY的参照物为【屏幕左上角】,注意包含状态栏区域
        case 3://若偏移值大于pop偏出屏幕的临界值,将取临界值。也即pop不可能会偏移出屏幕
        case 4://不管view设置的是哪一个,参照物都是整个屏幕的根布局
            pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
            pop.setHeight(20);
            if (position == 2) pop.showAtLocation(v, Gravity.NO_GRAVITY, 20, DensityUtils.getStatusBarHeight(this) + 10);//Gravity.NO_GRAVITY:相对屏幕左上角
            else if (position == 3) pop.showAtLocation(v, Gravity.TOP, 10, DensityUtils.getStatusBarHeight(this) + 10);//Gravity.TOP:相对屏幕正上方居中
            else pop.showAtLocation(v, Gravity.TOP, 100, DensityUtils.getStatusBarHeight(this));//临界值为 20/2=10,偏移值大于10时仅偏移10
            break;
        case 5://Gravity.BOTTOM:相对屏幕正下方居中,注意包含虚拟按键区域,并且此时yoff为正时表示向上偏移(而非向下偏移)
        case 6://
            pop.setWidth(DensityUtils.getScreenWidth(this) - 20);
            pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            if (position == 5) pop.showAtLocation(v, Gravity.BOTTOM, 0, DensityUtils.getBottomBarHeight(this));//Gravity.BOTTOM:相对屏幕正下方居中
            else if (position == 6) pop.showAtLocation(v, Gravity.BOTTOM, -10, DensityUtils.getBottomBarHeight(this) + 10);//此时yoff为正时表示向上偏移
            break;
        case 7://
            startActivity(new Intent(this, SecondActivity.class));
            break;
        }
    }
}

Activity2

public class SecondActivity extends Activity {
    private int num = 0;
    private PopupWindow pop;
    private int[] location = new int[2];;
    private View contentView;
    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        contentView = LayoutInflater.from(this).inflate(R.layout.view2null);
        pop = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        pop.setFocusable(true);//必备设置1
        pop.setBackgroundDrawable(new ColorDrawable(0x00ff0000));//必备设置2
        pop.setOutsideTouchable(true);//setFocusable(true)后这个设置就没用了
        pop.setAnimationStyle(R.style.popAniStyle);//设置动画所对应的style
    }
    public void onClick(View v) {
        v.getLocationOnScreen(location);// 获取锚点View在屏幕上的左上角坐标位置
        switch (num % 4) {
        case 0://右下
            pop.showAtLocation(v, Gravity.NO_GRAVITYlocation[0] + v.getWidth()location[1] + v.getHeight());
            break;
        case 1://右上
            pop.showAtLocation(v, Gravity.NO_GRAVITYlocation[0] + v.getWidth()location[1] - contentView.getHeight());
            break;
        case 2://左上
            pop.showAtLocation(v, Gravity.NO_GRAVITYlocation[0] - contentView.getWidth()location[1] - contentView.getHeight());
            break;
        default://左下
            pop.showAtLocation(v, Gravity.NO_GRAVITYlocation[0] - contentView.getWidth()location[1] + v.getHeight());
            break;
        }
        Toast.makeText(thisnum % 4 + "", Toast.LENGTH_SHORT).show();
        num++;
    }
}

工具类

public class DensityUtils {
    //******************************************************************************************
    //                                                                                    单位转换
    //******************************************************************************************
    /**像素密度*/
    public static float getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }
    /**  dp 转成为 px     */
    public static int dp2px(Context context, float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
    }
    /**  px 转成为 dp     */
    public static int px2dp(Context context, float pxValue) {
        return (int) (pxValue / getDisplayMetrics(context) + 0.5f);
    }
    /** sp转px */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics());
    }
    /** px转sp */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }
    //******************************************************************************************
    //                                                                                屏幕宽高
    //******************************************************************************************
    /**  获取屏幕宽  */
    public static int getScreenWidth(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
        return metric.widthPixels;
    }
     /** 获取屏幕高, 包含状态栏,但不包含虚拟按键 ,如1920屏幕只有1794  */
    public static int getScreenHeight(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
        return metric.heightPixels;
    }
    /**  获取屏幕宽  */
    public static int getScreenWidth2(Context context) {
        Point point = new Point();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
        return point.x;
    }
    /**  获取屏幕高,包含状态栏,但不包含某些手机最下面的【HOME键那一栏】,如1920屏幕只有1794  */
    public static int getScreenHeight2(Context context) {
        Point point = new Point();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
        return point.y;
    }
    /**  获取屏幕原始尺寸高度,包括状态栏以及虚拟功能键高度  */
    public static int getAllScreenHeight(Context context) {
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        try {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            Method method = Class.forName("android.view.Display").getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            return displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    //******************************************************************************************
    //                                                                        状态栏、标题栏、虚拟按键
    //******************************************************************************************
    /** 状态栏高度,单位px,一般为25dp  */
    public static int getStatusBarHeight(Context context) {
        int height = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height""dimen""android");
        if (resourceId > 0) {
            height = context.getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }
    /** 状态栏高度,单位px,【注意】要在onWindowFocusChanged中获取才可以 */
    public static int getStatusBarHeight2(Activity activity) {
        Rect rect = new Rect();
        //DecorView是Window中的最顶层view,可以从DecorView获取到程序显示的区域,包括标题栏,但不包括状态栏。所以状态栏的高度即为显示区域的top坐标值
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return rect.top;
    }
    /**标题栏的高度,【注意】要在onWindowFocusChanged中获取才可以*/
    public static int getTitleBarHeight(Activity activity) {
        int contentTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        return contentTop - getStatusBarHeight(activity);
    }
    /**获取 虚拟按键的高度     */
    public static int getBottomBarHeight(Context context) {
        return getAllScreenHeight(context) - getScreenHeight(context);
    }
}

常用API

构造方法

  • public PopupWindow(View contentView)
  • public PopupWindow(Context context)
  • public PopupWindow(View contentView, int width, int height)
  • public PopupWindow(View contentView, int width, int height, boolean focusable)
795730-20170220173922366-1076688854.png
参数说明
  • contentView为要显示的view;PopupWindow没有默认布局,它不会像AlertDialog那样只setTitle就能弹出来一个框,所以contentView必须设置。
  • width和height为要显示的view的宽和高,值为像素值或MATCHT_PARENT、WRAP_CONTENT;如果View是从xml得到的,那么xml的第一层view的大小属性将被忽略;必须设置宽和高,否则显示不出来。
  • focusable为是否能获得焦点
举例
View contentView = LayoutInflater.from( this) .inflate( R.layout.popuplayout, null) ;  
方法1:PopupWindow popupWindow = new PopupWindow( contentview,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) ;   
方法 2: PopupWindow popupWindow = new PopupWindow( contentview) ;
方法3:PopupWindwo popWnd = PopupWindow (context); 
            popWnd.setContentView(contentView);
            popupWindow.setWidth(LayoutParams. MATCHT_PARENT) ;           
            popupWindow.setHeight(LayoutParams.WRAP_CONTENT);

show方法

  • showAsDropDown(View anchor)  相对某个控件的位置(正左下方),无偏移。最终调用的是下面的方法
  • showAsDropDown(View anchor, int xoff, int yoff)  相对某个控件的位置,有偏移,xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;最终调用的是下面的方法
  • showAsDropDown(View anchor, int xoff, int yoff, int gravity)  【注:这个方法貌似不起作用】相对某个控件的某个位置,有偏移。gravity的默认值为DEFAULT_ANCHORED_GRAVITY= Gravity.TOP | Gravity.START
  • showAtLocation(View parent, int gravity, int x, int y)  相对于父控件(不管view设置的是哪一个,参照物都是整个屏幕的根布局)的某个位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移。
795730-20170220173923101-718880193.png
 
   
  1. /**
  2. * Displays the content view in a popup window anchored to the corner of
  3. * another view. The window is positioned according to the specified
  4. * gravity and offset by the specified x and y coordinates.
  5. * <p>
  6. * If there is not enough room on screen to show the popup in its entirety,
  7. * this method tries to find a parent scroll view to scroll. If no parent
  8. * view can be scrolled, the specified vertical gravity will be ignored and
  9. * the popup will anchor itself such that it is visible.
  10. * <p>
  11. * If the view later scrolls to move <code>anchor</code> to a different
  12. * location, the popup will be moved correspondingly.
  13. *
  14. * @param anchor the view on which to pin the popup window
  15. * @param xoff A horizontal offset from the anchor in pixels
  16. * @param yoff A vertical offset from the anchor in pixels
  17. * @param gravity Alignment of the popup relative to the anchor
  18. *
  19. * @see #dismiss()
  20. */
  21. public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)
  22. /**
  23. * <p>
  24. * Display the content view in a popup window at the specified location. If the popup window
  25. * cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams}
  26. * for more information on how gravity and the x and y parameters are related. Specifying
  27. * a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying
  28. * <code>Gravity.LEFT | Gravity.TOP</code>.
  29. * </p>
  30. *
  31. * @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from
  32. * @param gravity the gravity which controls the placement of the popup window
  33. * @param x the popup's x location offset
  34. * @param y the popup's y location offset
  35. */
  36. public void showAtLocation(View parent, int gravity, int x, int y)
showAtLocation的parent参数可以很随意,只要是activity中的view都可以。

setFocusable

setFocusable(boolean focusable) 设置PopupWindow是否获取焦点
 
   
  1. /**
  2. * <p>Changes the focusability of the popup window. When focusable, the
  3. * window will grab the focus from the current focused widget if the popup
  4. * contains a focusable {@link android.view.View}. By default a popup
  5. * window is not focusable.</p>
  6. *
  7. * <p>If the popup is showing, calling this method will take effect only
  8. * the next time the popup is shown or through a manual call to one of
  9. * the {@link #update()} methods.</p>
  10. *
  11. * @param focusable true if the popup should grab focus, false otherwise.
  12. *
  13. * @see #isFocusable()
  14. * @see #isShowing()
  15. * @see #update()
  16. */
  17. public void setFocusable(boolean focusable) {
  18. mFocusable = focusable;
  19. }

setOutsideTouchable

 
   
  1. /**
  2. * <p>Controls whether the pop-up will be informed of touch events outside
  3. * of its window. This only makes sense for pop-ups that are touchable
  4. * but not focusable, which means touches outside of the window will
  5. * be delivered to the window behind. The default is false.</p>
  6. *
  7. * <p>If the popup is showing, calling this method will take effect only
  8. * the next time the popup is shown or through a manual call to one of
  9. * the {@link #update()} methods.</p>
  10. *
  11. * @param touchable true if the popup should receive outside
  12. * touch events, false otherwise
  13. *
  14. * @see #isOutsideTouchable()
  15. * @see #isShowing()
  16. * @see #update()
  17. */
  18. public void setOutsideTouchable(boolean touchable) {
  19. mOutsideTouchable = touchable;
  20. }
2017-2-20

附件列表

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值