Получить меры всплывающего окна
Я уже настроил всплывающее окно, но хочу сосредоточить его под кнопкой (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);
}
Есть ли у кого-нибудь идея принять меры?
Ответы
Ответ 1
Вы не получите высоту или ширину представления, которое не было нарисовано на экране.
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 );
Ответ 2
По-другому:
/**
* @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;
}