dialog横竖屏切换时消失的解决方法

声明

  本文原创,转载请注明来自xiaoQLu http://www.cnblogs.com/xiaoQLu/p/3324764.html

dialog的生命周期依赖创建他的activity,怎么设置横竖屏切换时,dialog不重新创建,可以参考我的上一遍博客 http://www.cnblogs.com/xiaoQLu/p/3324503.html 。

按照上面的方法设置configChanges,是可以解决dialog消失的问题,但是会出现另一个问题,就是在android4.0的机器上,横屏变成竖屏后,dialog的宽度不变,这样子,就很难看,我们想要的是让他重新布局,随着屏幕变宽一点。

该怎么实现呢?

这里有一个比较巧妙的方法,

1、根据你的需要写一个根view的onLayout方法,如下,并写一个回调接口供dialog实现,我这里直接把dialog传进来了。

public class MiddleView extends RelativeLayout {
	private CreditsWallDialog mDialog;
	public MiddleView(Context context, CreditsWallDialog dialog) {
		super(context);
		this.mDialog = dialog;
	}

	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		mDialog.onLayoutCallBack(left, top, right, bottom);
	}

}

2、dialog的layout中把MiddleView作为根视图使用,如果是代码布局的话可以这样 setContentView(new MiddleView(mContext, this));

<?xml version="1.0" encoding="utf-8"?>
<cn.richinfo.jifenqiang.widget.MiddleView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- 这里添加自己的控件 -->

</cn.richinfo.jifenqiang.widget.MiddleView>

3、在dialog中实现步骤1中的回调方法

    public void onLayoutCallBack(int left, int top, int right, int bottom) {
        DisplayWindow win = DisplayWindow.getDisplayWindow(mContext);
        int width = (int) ((double) win.width * scale_width);
        int height = (int) ((double) win.height * scale_height);
        if (width == this.mWidth && height == this.mHeight) {
            LogUtils.println("lcq:onLayCallbck is same to last...");
            return;
        }
        setWindowAttribute(width, height);
    }

4、重新设置windows的宽度和高度

private void setWindowAttribute(int width, int height) {
        Window window = getWindow();
        android.view.WindowManager.LayoutParams windowParams = window
                .getAttributes();
        windowParams.width = width;
        windowParams.height = height;
        DisplayWindow dWin = DisplayWindow.getDisplayWindow(mContext);
        int adjustPix = dWin.dipToPix(16);
        windowParams.width += adjustPix;
        windowParams.height += adjustPix;
        if (windowParams.width > dWin.width) {
            windowParams.width = dWin.width;
        }
        if (windowParams.height > dWin.height) {
            windowParams.height = dWin.height;
        }
        this.mWidth = width;
        this.mHeight = height;
        window.setAttributes(windowParams);
    }

5、在dialog的构造函数中调用一次 setWindowAttribute 方法,这个主要是保证切初始时的窗口和 横屏切回到竖屏时的窗口大小一致

 

这里主要是讲一种思路,仔细看下,就大概知道思路了,主要是通过横竖屏切换时,view的onLayout会被重新调用来实现的,中间加上对窗口的宽度和高度的计算,由于onLyaout会被调用多次,所以有些重复的调用可以用return返回掉。

 

posted @ 2013-09-16 21:42  muzhi121  阅读(8586)  评论(0编辑  收藏  举报