PopupWindow自定义位置显示

来源:互联网 发布:如何描述淘宝店铺 编辑:程序博客网 时间:2024/06/16 18:36

一、概述

在Android中弹出式菜单(以下称弹窗)是使用十分广泛的一种菜单呈现方式,弹窗为用户交互提供了便利。关于弹窗的实现大致有以下两种方式AlertDialog和PopupWindow,当然网上也有使用Activity并配合Dialog主题的方式实现弹窗,有兴趣的朋友也可以去研究一下。对于AlertDialog和PopupWindow两者最主要的区别就是显示的位置问题:
(1)AlertDialog在位置显示上是固定的
(2)PopupWindow相对比较随意,能够在主屏幕的任意位置显示。


二、效果图

这里写图片描述


三、代码

(1)MainActivity中的代码:

public class MainActivity extends AppCompatActivity {    private int x;    private int y;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        //  获得点击屏幕的坐标        x = (int) event.getX();        y = (int) event.getY();        //  加载PopupWindow 对应的界面        LayoutInflater inflater = getLayoutInflater();        final View popupView = inflater.inflate(R.layout.popup_entry_layout,null);        //  创建PopupWindow 对象        final PopupWindow popupWindow = new PopupWindow(popupView,400,100); // 第二、第三个参数用来设置弹窗的大小,也可以用WRAP_CONTENT        //  设置位置        popupWindow.showAtLocation(popupView, Gravity.NO_GRAVITY,x,y);        new Handler().postDelayed(new Runnable() {            @Override            public void run() {                //  1秒后关闭该弹窗                popupWindow.dismiss();            }        },1000);        return true;    }}

(2)布局文件中的代码省略。


1 0