使用樣式文件,在values 目錄下新建styles.xml文件,編寫如下代碼:
<resources>
<style name="dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">@android:color/black</item>
<item name="android:windowBackground">@null</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
<style name="dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">false</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">@android:color/black</item>
<item name="android:windowBackground">@null</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
調用時,使用AlerDialog的接口類,Dialog 接口編寫如下代碼:
Dialog dialog = new Dialog(SetActivity.this, R.style.dialog);
dialog.setContentView(R.layout.test);
dialog.show();
dialog.setContentView(R.layout.test);
dialog.show();
下面我們查看一下Dialog的源碼文件,裏面的構造函數爲如下:
public Dialog(Context context, int theme) {
mContext = new ContextThemeWrapper(
context, theme == 0 ? com.android.internal.R.style.Theme_Dialog : theme);
mWindowManager = (WindowManager)context.getSystemService("window");
Window w = PolicyManager.makeNewWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER);
mUiThread = Thread.currentThread();
mDismissCancelHandler = new DismissCancelHandler(this);
}
mContext = new ContextThemeWrapper(
context, theme == 0 ? com.android.internal.R.style.Theme_Dialog : theme);
mWindowManager = (WindowManager)context.getSystemService("window");
Window w = PolicyManager.makeNewWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER);
mUiThread = Thread.currentThread();
mDismissCancelHandler = new DismissCancelHandler(this);
}
這裏面我們可以看出,Android 使用了默認的構造函數爲Dialog 設置樣式,如果沒有爲其設置樣式,即默認加載事先編寫好的樣式文件,Dialog 一共由多個9.png的圖片構成,大部分都是帶有邊框的9.png圖片,所以就是爲什麼我們上邊的樣式文件要將其背景去除掉。這個東西搞了我好久,希望對你有幫助
前後效果對比
未設置前:
設置後: