如何正确获取GridView项目位置x,y

时间:2017-03-02 10:50:57

标签: android gridview position

我想将对话框的位置设置在点击它的同一位置..就像这样

enter image description here

但我得到了这个

enter image description here

这是我的位置对话框的代码..

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        float positionX = v.getX();
        float positionY = v.getY();

        LinearLayout container = (LinearLayout) gvGrid.getFocusedChild();

        dialog = new Dialog(CW_Emergency.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.view_pager_layout);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        //position of popup
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.x = (int) positionX;
        params.y = (int) positionY;

        ViewPagerAdapter adapter = new ViewPagerAdapter(container, CW_Emergency.this);
        viewPager = (ViewPager) dialog.findViewById(R.id.view_pager);

        dialog.show();



    }

请告诉我如何针对所有屏幕尺寸正确定位

2 个答案:

答案 0 :(得分:0)

您可以使用PopupWindow。

 mPopupWindow = new PopupWindow(
                    customView,
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT
            );

并显示

mPopupWindow.showAsDropDown(ItemInGridView, 0, -1 * ItemInGridView.getHeight(), Gravity.LEFT);

答案 1 :(得分:0)

根据我在正确位置显示对话框 PopupMenu 会更方便和简单。实现PopupMenu ......

  1. 首先,您必须在菜单资源文件夹

    中创建菜单资源文件
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_option1"
      android:title="Option 1"
      />
    <item android:id="@+id/menu_option2"
      android:title="Option 2"
      />
    </menu>
    
  2. onItemClick()方法中实现以下代码

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    
    PopupMenu popup = new PopupMenu(this, v);
    // Inflate the menu from xml
    popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
    // Setup menu item selection
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.menu_option1:
                Toast.makeText(MainActivity.this, "Option 1", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menu_option2:
                Toast.makeText(MainActivity.this, "Option 2", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return false;
            }
        }
    });
    // Show the menu
    popup.show();
    
     }
    
  3. PopupMenu将准确显示在您要点击的视图附近。