前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >无法重新布局的问题

无法重新布局的问题

原创
作者头像
用户10521372
发布2023-04-21 11:27:50
4060
发布2023-04-21 11:27:50
举报
文章被收录于专栏:android自用android自用

onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager

出现这个异常来自于在Fragment中动态添加一个布局,切换的时候崩溃

写法如下:

代码语言:javascript
复制
getLayoutInflater().inflate(R.layout.layout_footer...)

调用的是Activity的getLayoutInflater 这句代码原本是没有什么问题的,但是在Fragment中使用就有问题了。

解决办法:

换一种写法

代码语言:javascript
复制
View view = inflater.inflate(R.layout.fragment_dialog_enum, null);
Button button = (Button) LayoutInflater.from(view.getContext()).inflate(R.layout.fragment_bottom_button, null);

所以,在Activity中可以直接用getLayoutInflater().inflate的方式,

在Fragment中要用LayoutInflater.from(getActivity()).inflate。

源码:

代码语言:javascript
复制
   /**
     * Returns the cached LayoutInflater used to inflate Views of this Fragment. If
     * {@link #onGetLayoutInflater(Bundle)} has not been called {@link #onGetLayoutInflater(Bundle)}
     * will be called with a {@code null} argument and that value will be cached.
     * <p>
     * The cached LayoutInflater will be replaced immediately prior to
     * {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} and cleared immediately after
     * {@link #onDetach()}.
     *
     * @return The LayoutInflater used to inflate Views of this Fragment.
     */
    @NonNull
    public final LayoutInflater getLayoutInflater() {
        if (mLayoutInflater == null) {
            return performGetLayoutInflater(null);
        }
        return mLayoutInflater;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
目录
  • onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager
    • 解决办法:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档