inflater.inflate(R.layout.) 找不到 Fragment.xml

inflater.inflate(R.layout.) doesn't find Fragment.xml

我遇到问题,命令 view =inflater.inflate(R.layout. 找不到我的片段 xml

这是错误:

public class FragmentName extends Fragment {

    View view;

    public FragmentName() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view =inflater.inflate(R.layout.name_fragment,container,false);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

}

这是我的XML

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/view_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Charackter Name"
        android:textColor="@color/tabtextcolor"
        android:textSize="20sp"
        android:textStyle="bold"></com.google.android.material.textview.MaterialTextView>
    </LinearLayout>

我没有发现我的错误。我重建并清理了项目。

只需更改您的 return 声明

public class FragmentName extends Fragment {

    View view;

    public FragmentName() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view =inflater.inflate(R.layout.name_fragment,container,false);
        return view;
    }

}

不要

return super.onCreateView(inflater, container, savedInstanceState);

retun View's object

纠正你的onCreateView()方法。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.name_fragment, container, false);
    MaterialTextView view_id = (MaterialTextView) view.findViewById(R.id.view_id);
    return view;

那么Clean-Rebuild你的IDE.