源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-10-08 19:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PopupWindow自定义位置显示的实现代码
[b]一、概述[/b] 在Android中弹出式菜单(以下称弹窗)是使用十分广泛的一种菜单呈现方式,弹窗为用户交互提供了便利。关于弹窗的实现大致有以下两种方式AlertDialog和PopupWindow,当然网上也有使用Activity并配合Dialog主题的方式实现弹窗,有兴趣的朋友也可以去研究一下。对于AlertDialog和PopupWindow两者最主要的区别就是显示的位置问题: (1)AlertDialog在位置显示上是固定的 (2)PopupWindow相对比较随意,能够在主屏幕的任意位置显示。 [b]二、效果图[/b] [img]http://files.jb51.net/file_images/article/201710/2017103014353532.png[/img] [b]三、代码[/b] (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)布局文件中的代码省略。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部