0

I need to access the view that has been inflated in a DialogFragment. inflater and container appear to be unresolved but yet when I add these to the parentheses of onCreateDialog, the overrides nothing error is returned. What is the correct solution in this case?

class MyDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(activity)
        val rootView = inflater.inflate(R.layout.dialog_sample, container, false)

        lateinit var tabLayout: TabLayout
        lateinit var viewPager: ViewPager

        builder.setIconAttribute(R.attr.imgNight)
        builder.setTitle("My Program")
        builder.setView(rootView)
        builder.setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.dismiss() }

        tabLayout = rootView.findViewById(R.id.tabLayout)
        viewPager = rootView.findViewById(R.id.viewPager)

        val adapter = CustomAdapter(childFragmentManager)
        adapter.addFragment("Boy", CustomFragment.createInstance("Oscar"))
        adapter.addFragment("Girl", CustomFragment.createInstance("Stacy"))
        adapter.addFragment("Robot", CustomFragment.createInstance("Aeon"))
        viewPager.adapter = adapter
        tabLayout.setupWithViewPager(viewPager)

        return builder.create()
    }
}
wbk727
  • 8,017
  • 12
  • 61
  • 125

1 Answers1

0

The container pass null since there isn't a parent view. As for the inflater use LayoutInflater.from(requireContext).

You can then use the view in the dialog builder.

wbk727
  • 8,017
  • 12
  • 61
  • 125
Ge3ng
  • 1,875
  • 1
  • 24
  • 38
  • So `LayoutInflater.from(requireContext)` replaces `inflater`? `Null` should not be used as the view root. – wbk727 Feb 18 '19 at 00:48
  • Yes like so `val rootView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_sample, null, false)` – Ge3ng Feb 18 '19 at 00:53
  • `null` returns a warning: ‘Avoid passing `null` as the view root’ – wbk727 Feb 18 '19 at 00:55
  • Yes this is just a warning but it works and doesn't error out. There are a few ways around but they are error prone and depend on proper timing which fails across the large range of android devices. – Ge3ng Feb 18 '19 at 01:02
  • 1
    There is another option which is to use `onCreateView` and don't use `AlertDialog` or `onCreateDialog`. The drawback is you have to handle all view components including the title and the buttons, but you won't have any warnings. – Ge3ng Feb 18 '19 at 01:29
  • Running the code causes the app to crash. See [this question](https://stackoverflow.com/questions/54749729/dialogfragment-not-appearing) – wbk727 Feb 18 '19 at 22:55
  • Please post the stacktrace? – Ge3ng Feb 19 '19 at 03:08