ViewPager in DialogFragment - IllegalStateException: Fragment does not have a view

后端 未结 4 1717
渐次进展
渐次进展 2020-12-08 07:24

What I want to achieve

  • From a FragmentActivity show a dialog when clicking an Action Button in the Action Bar
  • DialogFragment
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 07:59

    I think I just ran into this same problem and learned a few things by looking at the source for DialogFragment.

    It looks like even though overriding onCreateDialog(...) is a valid way to create a custom dialog, it will result in the DialogFragment having a null View, just like the error message says. In most cases this is fine - the DialogFragment doesn't need a View to show a Dialog, but if you want to nest fragments further (like you do), this won't fly.

    Considering that you want to interact with an AlertDialog.Builder, there is really no perfect solution that I can see, but you've got a few options:

    1. Create the buttons in your dialog as part of the View (not using AlertDialog.Builder). You do this by overriding onCreateView instead of onCreateDialog. You should be able to get the functionality you mention by putting the buttons in their own fragment. We do something similar at my gig, and I very much prefer this method.
    2. Implement your own type that inherits from Fragment and that mirrors the DialogFragment in every way except allowing what you need. This shouldn't be too scary as DialogFragment is only ~400 and is heavily commented. Could be fun.
    3. Use a regular PagerAdapter instead of a FragmentPagerAdapter. This way it won't matter that your DialogFragment doesn't have a View.

提交回复
热议问题