点击按钮附近的对齐弹出窗口

时间:2016-05-31 11:36:01

标签: android

我有一个布局的自定义弹出窗口。我需要在a_btn点击后给出一个x,y坐标以显示弹出窗口。这可以是不同手机中的不同位置。

但我想在上方显示弹出窗口并触摸a_btn

我该如何实现呢。帮助我

我显示弹出窗口的代码:

a_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());
            popup.showAtLocation(relative, Gravity.NO_GRAVITY, coordinateTop, 100);
            //popup.showAsDropDown(location_popup_view,  2, 2);


        }
    });

2 个答案:

答案 0 :(得分:1)

使用此代码可以帮助您

a_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
             Rect r = locateView(v);    
    LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());
            popup.showAtLocation(layout, Gravity.TOP | Gravity.LEFT, r.right, r.bottom);


        }
    });



    public static Rect locateView(View v) {
            int[] loc_int = new int[2];
            if (v == null)
                return null;
            try {
                v.getLocationOnScreen(loc_int);
            } catch (NullPointerException npe) {
                return null;
            }
            Rect location = new Rect();
            location.left = loc_int[0];
            location.top = loc_int[1];
            location.right = loc_int[0] + v.getWidth();
            location.bottom = loc_int[1] + v.getHeight();
            return location;
        }

答案 1 :(得分:1)

我使用了popup.showAsDropDown(a_btn,0,0);

而不是 popup.showAtLocation(relative, Gravity.NO_GRAVITY, coordinateTop, 100);

并给了xoff和yoff。

a_btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {    
LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popup_view = lInflater.inflate(R.layout.popup_a, null);
        final PopupWindow popup = new PopupWindow(popup_view,200,200,true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new ColorDrawable());
        popup.showAsDropDown(a_btn,0,0);


    }
});