获取弹出窗口的度量

问题描述 投票:14回答:2

我已经设置了弹出窗口,但是我想将它放在按钮(View v)下面,需要点击它才能打开它:

public void showPopup(Context c, View v){
    int[] location = new int[2];
    v.getLocationOnScreen(location);

    ViewGroup base = (ViewGroup) getView().findViewById(R.id.pup_pattern);  
    LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View pupLayout = inflater.inflate(R.layout.linearlayout_popup, base);

    final PopupWindow pup = new PopupWindow(pupLayout, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

    int x = location[0] - (int) ((pupLayout.getWidth() - v.getWidth()) / 2 ); // --> pupLayout.getWidth() gives back -2?
    int y = location[1] + v.getHeight() + 10;

    pup.setFocusable(true);
    pup.showAtLocation(v, Gravity.NO_GRAVITY, x, y);
}

有人有想法得到措施吗?

android popupwindow measurement
2个回答
28
投票

您将无法获得未在屏幕上绘制的视图的高度或宽度。

pupLayout.getWidth() //这将给你0

你需要得到像这样的宽度

int width = MeasureSpec.makeMeasureSpec(0, MeasureSpec. UNSPECIFIED);

像这样使用它

View pupLayout = inflater.inflate(R.layout.linearlayout_popup, base);
pupLayout.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

int x = location[0] - (int) ((pupLayout.getMeasuredWidth() - v.getWidth()) / 2 );

-1
投票

其他方式:

/**
 * @return Point object which:<br>
 * point.x : contains width<br>
 * point.y : contains height
 */
public static Point getViewSize(View view) {
    Point size = new Point();
    view.post(new Runnable() {
        @Override
        public void run() {
            size.set(view.getWidth(), view.getHeight());
        }
    });
    return size;
}
© www.soinside.com 2019 - 2024. All rights reserved.