无法重新布局的问题

2023-04-21 11:27:50 浏览数 (1)

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;
    }

0 人点赞