栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

一、概述

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/157423.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号