對於習慣了用layout_weight來設計頁面佈局的小夥伴們來說,自定義Dialog/Popwindow內容的時候,或許也會想着用它來解決位於屏幕上的自適應問題吧!至少小編我就是這麼幹活的,並且也都沒有遇上哪些個問題。可如今再自己定義Dialog的時候,卻意外發現Dialog彈出效果顯示異常。
異常 [ 對話框內容不顯示 ]
出現以上異常情況,當然不要抱着僥倖的心理嘗試點擊對話框內的可能隱藏內容,因爲不會有任何響應的(已幫助嘗試)。但如果設置了點擊彈窗以外的內容可退出,那麼效果依然是可見的。只是爲何會出現這種問題呢?估摸着可能是設置自定義style主題的原因,固索性前去勘察,並 嘗試更改背景顏色 ,未果。
<style name="Translucent_NoTitle" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:background">@android:color/transparent</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
</style>
異常 [ 對話框存在局部背景 ]
修改style對應的背景顏色屬性值沒有起效着實讓人想不通,於是乎緊跟着節奏繞回代碼當中 引用其他style (解決問題關鍵後引用原style)。運行結果如上,此刻確實是能過顯示出彈出框的內容了,但出現局部背景又或是哪幾個意思?躍入其他style嘗試重寫並修改屬性值從而解決局部背景的問題,仍未果。
/**
* 創建彈出對話框
*/
public RemindDialog create() {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ... 這裏將自定義Style的引用修改爲系統Style的應用
final RemindDialog dialog = new RemindDialog(mContext, R.style.Theme_AppCompat_Dialog);
View layout = inflater.inflate(R.layout.dialog_common_remind, null);
dialog.addContentView(layout, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// ...這裏忽略中間操作
dialog.setContentView(layout);
dialog.setCancelable(false);
return dialog;
}
異常解決 [ 調皮的layout_weight ]
以上嘗試處理問題的方式主要都是停留在對於style的…就這樣過了一小段時間,小編回想自定義View的佈局設置,從一個抽象的角度上去遐想其運行的結果定是沒有問題的。但都這樣了只能回去改改佈局了,結果如標題所述,確確實實就是佈局上自適應“水平”權重設置的問題(?誰能告訴小編爲何彈出框上下也出現局部突出)。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5">
<!-- 此處忽略具體內容 -->
</LinearLayout>
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" />
</LinearLayout>
最後修改的佈局內容如下。如果真的有必要實現自適應的話,其實百分比佈局也是個不錯的選擇。像這種這麼簡單的問題,今後小夥伴們也要多多注意咯(當然,可能說的是那種習慣用layout_weight解決自適應問題的大咖)。如果有更好的自定義實現,請務必留下,但如果你對自定義Dialog出現局部背景有其他見解的,也歡迎提出來一同參考!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="55dp"
android:layout_marginRight="55dp">
<!-- 此處忽略具體內容 -->
</LinearLayout>
</LinearLayout>