首页 > 系统 > Android > 正文

PopupWindow自定义位置显示的实现代码

2019-12-12 01:46:54
字体:
来源:转载
供稿:网友

一、概述

在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)布局文件中的代码省略。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表