android – 获取弹出窗口的措施

前端之家收集整理的这篇文章主要介绍了android – 获取弹出窗口的措施前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经设置了弹出窗口,但是我想把它放在按钮下面(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);
}

有人有办法采取措施吗?

解决方法

您不会得到视图的高度或宽度,该视图尚未在屏幕上绘制.

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 );
原文链接:https://www.f2er.com/android/312084.html

猜你在找的Android相关文章