標籤:android dialog dialogfragment
小問題,記錄下~
Android4.0以後開始推薦使用DialogFragment代替Dialog。Android的官方文檔中給了兩個樣本:
- 一個
Basic Dialog
樣本了如何自訂視窗內容——重寫onCreateView方法。
- 一個
Alert Dialog
樣本了如何自訂彈窗的正負按鈕——重寫onCreateDialog方法。
好的,那麼問題來了
在實際應用中經常是需要既自訂視窗內容、又需要自訂按鈕的。
這時候如果我們按圖索驥,把DialogFragment的onCreateView和onCreateDialog方法都重寫的話,會發現——Bong!異常~ 諸如“AndroidRuntimeException: requestFeature() must be called before adding content”的就出現了。
這個異常出現的原因可以看:stackoverflow的這個問題中Freerider的答案以及下面評論。
摘抄一下:“ You can override both (in fact the DialogFragment says so), the problem comes when you try to inflate the view after having already creating the dialog view. You can still do other things in onCreateView, like use the savedInstanceState, without causing the exception.”
然後是解決方案:
既然兩個方法不能同時重寫,所以就選擇一個進行重寫:
重寫onCreateDialog方法,參照官方樣本即可以自訂按鈕,然後對其作修改,使之能自訂view——在AlertDialog.Builder進行create()建立dialog之前,使用AlertDialog.Builder的setView(view)方法,其中view是自定view。
來感受一下區別~
這是Google給的樣本:
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt("title"); return new AlertDialog.Builder(getActivity()) .setIcon(R.drawable.alert_dialog_icon) .setTitle(title) .setPositiveButton(R.string.alert_dialog_ok, 。。。) .setNegativeButton(R.string.alert_dialog_cancel, 。。。) .create();}
這是修改之後的:
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) { //inflater在前面建構函式中執行個體化 View v = inflater.inflate(R.layout.dialog,null); imageGridView = (GridView) v.findViewById(R.id.gridViewImage); //自訂view,bla~bla~ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); return builder.setView(v) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(title) .setCancelable(false) .setPositiveButton(R.string.alert_dialog_ok, 。。。) .setNegativeButton(R.string.alert_dialog_cancel, 。。。) .create();}
Also at: http://www.barryzhang.com/archives/396
Android:自訂DialogFragment的內容和按鈕