聲明
本文原創,轉載請注明來自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返回掉。