简体   繁体   中英

Cannot resolve 'findViewById' method in Fragment RecyclerView

I'm new to android studio, I was trying to create RecyclerView on Fragment. I was following a tutorial but I still get message ' Cannot resolve 'findViewById'

I've tried doing:

RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerView);

But ended up receiving error:

 Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

Here is the code:

package com.example.app;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Articles extends Fragment {



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

        NewsList[] myListData = new NewsList[] {
                new NewsList("Article 1", "Some Author"),
                new NewsList("Article2", "Some Author"),
                new NewsList("Article3", "Some Author"),

        };
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        NewsAdapter adapter = new NewsAdapter(myListData);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

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

        return inflater.inflate(R.layout.fragment_create, container, false);
    }


}

How can I resolve this issue?

Your view is not yet inflated which is the reason it cannot be found. Move your code from onCreate to onViewCreated fragment lifecycle.

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // your view is discoverable here
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    }

Add these variables:

View root;
RecyclerView recyclerView;

Change your onCreateView to this:

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.fragment_profile, container, false);
    recyclerView = root.findViewById(R.id.recyclerView);
    return root;
}

and lastly - make sure that your recyclerview within your XML file has the following:

 android:id="@+id/recyclerView"

For your example, your List (myListDatae) must be inside the NewsAdapter class as a field variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM