Search code examples
javaandroidfragmentfindviewbyid

"cannot resolve findviewbyid in fragment" error


I'm trying to move Floating Action Button into my Fragment. But I'm getting an error about findViewById. It's "Cannot resolve method 'findViewById'

I researched, i found so many things but i'm not good at this. Can anyone explain me how can i solve this error? I tried "Invalidate Caches/Restart" and "Clean and Rebuild Project", but it didn't work.

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

    //Floating Action Button
    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // intent
        }
    });

}

Solution

  • findviewById() do not belongs to Fragment class, but Activity.

    You said you're inside a Fragment and want to access some view in the Activity, you must use getActivity().findViewById(R.id.fab).