获取

2013-04-07 33 views
11

我已经设置了弹出窗口弹出窗口的办法,但我想居中按钮(视图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); 
} 

有没有人一个想法来获得措施?

回答

21

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

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);