Android Dialog 設定圓角無效
阿新 • • 發佈:2018-12-08
這兩天有一個需求:設定dialog圓角,寫完後發現並沒有達到效果,以前也碰到這個問題,這裡記錄下解決方案,便於查閱。也有百度去查詢原因,卻沒有發現合適的解答,當然更可能是我沒找到,還是自己解決吧。
Dialog與DialogFragment 解決方案一致:只要設定背景透明解決問題了。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); setContentView(view); setCancelable(true); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //設定背景透明 getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); View view = View.inflate(getActivity(), R.layout.dialog_zntchain, null); return view; }
看到這裡,不難明白,應該是google自己設定了預設的背景,雖然我們設定了view為圓角,但是在掛在已有背景下,我們就是自然看不到,看下原始碼,google也有說道透明問題。
/** * Change the background of this window to a Drawable resource. Setting the * background to null will make the window be opaque. To make the window * transparent, you can use an empty drawable (for instance a ColorDrawable * with the color 0 or the system drawable android:drawable/empty.) * * @param resId The resource identifier of a drawable resource which will * be installed as the new background. */ public void setBackgroundDrawableResource(@DrawableRes int resId) { setBackgroundDrawable(mContext.getDrawable(resId)); }