如何在更改android中的方向时恢复弹出窗口的位置?

时间:2012-10-23 08:03:38

标签: android

我试图在用户触摸屏幕的任何地方显示弹出窗口。我能够在所需的位置显示弹出窗口。但问题是当弹出窗口处于纵向模式时如果我在横向模式下更改弹出窗口显示在相同位置的方向,因为弹出窗口与横向模式中的视图重叠,当我们将方向横向更改为纵向时会出现同样的问题。我的要求如下 1.更改方向时不要忽略弹出窗口。 2.当方向发生变化时,动态更改所有弹出窗口的位置,使视图不重叠(弹出窗口与图像不重叠)。例如,当我将方向纵向更改为横向弹出窗口时,位置将向上移动。

private void showPopup(final Activity context, Point p) {
    int popupWidth = 200;
    int popupHeight = 150;
    boolean showEditText = true;
    // Inflate the popup_layout.xml
    LinearLayout viewGroup = (LinearLayout) context
            .findViewById(R.id.popup);
    LayoutInflater layoutInflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow(context);
    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(popupHeight);
    popup.setFocusable(false);
    popup.setOutsideTouchable(false);

    // Some offset to align the popup a bit to the right, and a bit down,
    // relative to button's position.
    int OFFSET_X = 5;
    int OFFSET_Y = 5;

    // Clear the default translucent background
    popup.setBackgroundDrawable(new BitmapDrawable());

    // Displaying the popup at the specified location, + offsets.
    popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y
            + OFFSET_Y);

    final Button addname = (Button) layout.findViewById(R.id.addName);

}

1 个答案:

答案 0 :(得分:0)

我知道这不是一个好的解决方案,但是我们可以这样做

popup设为类级对象

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
                showPopup(...);
            }
        }
    },500);
}