findViewById() not finding custom view but it exists in layout
Because in the constructor, you had super(context)
instead of super(context, attrs)
.
Makes sense, if you don't pass in the attributes, such as the id, then the view will have no id and therefore not be findable using that id. :-)
Answer ref : findViewById() returns null for custom component in layout XML, not for other components
Can't retrieve view with findViewById
Your text_view
is in the fragment layout and not in the activity layout. It won't be in the activity view hierarchy yet in onCreate()
and findViewById()
won't find it, returning null
. The NPE in your stacktrace is caused by trying to invoke a method on this null
.
Move the findViewById()
and related code to the fragment's onCreateView()
, calling findViewById()
on the rootView
inflated there.
Cannot resolve 'findViewById' method in Fragment 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"
findViewById not working for specific view
Change the super
call in your two-parameter constructor to:
super(context, attrs);
When a View
is inflated from a layout, the XML attributes and their values are passed into the two-parameter constructor via the AttributeSet
. If you don't pass that to the superclass, the id
you've specified in the XML is never set on the View
, so findViewById()
won't find it with the given ID.
Cannot resolve findViewById in fragment
Firstly, you are calling findViewById()
after the return statement so they wont be executed at all. Next, you need to call findViewById()
on the context of a view as in view.findViewById(int);
so rewrite the code as :
View v = inflater.inflate(R.layout.activity_slide__teacher_add,container,false);
teacher_id_number = v.findViewById(R.id.teacher_id_number); //Note this line
//other tasks you need to do
return v;
making sure the return
is the last statement of the function.
Related Topics
How to Resume Existing Fragment from Backstack
How to Send a File in Android from a Mobile Device to Server Using Http
How to Send String from One Activity to Another
Wait Firebase Async Retrieve Data in Android
Warning: This Asynctask Class Should Be Static or Leaks Might Occur
Firebase Firestore Variable Name Changed
How to Set Mobile System Time and Date in Android
Html.Fromhtml Deprecated in Android N
How to Add Calendar Events in Android
Android Create Shortcuts on the Home Screen
How to Get Current Time from Internet in Android
How to Sort Firebase Records by Two Fields (Android)
Android Writing Logs to Text File
How to Create Circular Progressbar in Android