Android:自訂DialogFragment的內容和按鈕

來源:互聯網
上載者:User

標籤: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的內容和按鈕

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.