【问题标题】:How to resolve error findViewById error in android fragment如何解决android片段中的错误findViewById错误
【发布时间】:2021-01-06 01:07:28
【问题描述】:

我正在尝试在我的片段中添加 recyclerview,但是当我单击导航抽屉项目时出现错误。

尝试在空对象引用上调用虚拟方法“android.view.View android.view.View.findViewById(int)” 在 com.example.myapplication.fragment.Books.onCreate(Books.java:45)

如何解决错误或建议使用 recyclerview 在片段中加载 json 数据的教程。在recyclerview 上有点击事件。点击项目打开带有数据的新片段。

这是我的代码

public class Books extends Fragment {

    private BooksModel booksViewModel;

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private List<BooksModel> bookLists;
//    Context context;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerViewBook); //Line 45 Error
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        bookLists = new ArrayList<>();

        for(int i=0; i<=10; i++){
            BooksModel bookList = new BooksModel(
                    "",
                    "Title " + (i + 1),
                    "This is Auther"
            );

            bookLists.add(bookList);

            adapter = new BooksAdapter(bookLists,this);
            recyclerView.setAdapter(adapter);
        }
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        booksViewModel =
                new ViewModelProvider(this).get(BooksModel.class);
        View root = inflater.inflate(R.layout.fragment_books, container, false);
        final TextView textView = root.findViewById(R.id.text_book );
        booksViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

【问题讨论】:

    标签: android android-studio android-layout android-fragments


    【解决方案1】:

    onCreate() 运行 之前 onCreateView()。您应该将所有代码移至onViewCreated(),它会直接将View 传递给您(这意味着您根本不必调用getView())。

    【讨论】:

    • 在将代码移动到 onCreateView 方法后出现此错误example.myapplication.fragment.Books.onCreateView(Books.java:61)
    • 我不是说你应该把代码移到onCreateView()——我说把它移到onViewCreated()方法中(这是Fragment的另一种方法)。
    • @jkdobariya 参考这个,以便更好地理解片段以及如何使用它。 developer.android.com/guide/fragments/lifecycle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多