试试这个:
anchorView.getLocationOnScreen(location);
位置是一个数组:
int location[] = new int[2];
anchorView 是您的视图。
所以你的函数可能看起来像:
public getLocation(View anchorView){
int location[] = new int[2];
anchorView.getLocationOnScreen(location);
}
如果您想在该位置显示不同的视图,只需执行以下操作:
yourView.showAtLocation(anchorView, Gravity.NO_GRAVITY,
location[0], location[1] + anchorView.getHeight());
另外请注意,您可以操作 location[0] 和 location[1] 中的值。祝你好运:)
编辑
这是一个完整的例子,我用它在一个按钮下面显示一个片段,这个过程在按钮被点击时发生:
public void showPopup(View anchorView) {
View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button proceed = (Button)popupView.findViewById(R.id.button1);
Button cancel = (Button)popupView.findViewById(R.id.button2);
cb = (CheckBox)popupView.findViewById(R.id.checkBox1);
proceed.setOnClickListener(onProceed);
cancel.setOnClickListener(onCan);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable());
int location[] = new int[2];
anchorView.getLocationOnScreen(location);
popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
location[0], location[1] + anchorView.getHeight());
}
上面将导致一个弹出窗口,就在点击的视图下方。
popup_layout 是要膨胀的 XML 布局文件。