Properly creating a fragment in a PopupWindow

我是研究僧i 提交于 2019-11-28 19:33:02

Inflating the layout directly will not cause it it to instantiate the fragment; Android would just consider it a mere coincidence that both the fragment and the activity are trying to refer to the same layout file.

Ordinarily, you would use FragmentManager.add(int,Fragment) to add a fragment to a layout. However, the container id that you specify has to be part of the layout of the current Activity, and this is not the case with a PopupWindow. Instead, you would have to add the fragment to the fragment manager without specifying a container, and then sometime later in the fragment (e.g. onStart()) you can show a PopupWindow. This is precisely how DialogFragment works, and since there is already lots of support for it, I would suggest you switch to using a DialogFragment instead.

With your Fragment code, simply extend DialogFragment instead of Fragment, and use DialogFragment.show(FragmentManager,String) to display it. You can get rid of the default border by calling setStyle(DialogFragment.STYLE_NO_FRAME, getTheme()) in the onCreate method. You can still add this Fragment to a layout (as you say, on a phone you do not want it to be shown as a popup) and it will work as how you expect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!