I'm asking you how to use findViewById in the fragment~~

Asked 2 years ago, Updated 2 years ago, 39 views

I've just used the Android studio, so I'm a beginner who doesn't know anything(Crying) I don't know how to use findViewById to use fragment. If you do so, an error occurs.

Error: Attempt to invoke virtual method 'android.view.view android.view.findViewById(int)' on a null object reference at com.example.myapplication1.Fragment1.onCreate

fragment

2022-09-20 20:17

2 Answers

You can use it after the onViewCreated call, not onCreate.


2022-09-20 20:17

fragment ctrl from your code +, you press o override members, window displays and I come up are taken from a parent class to class members that may be overwritten.

If you type onViewCreated with your keyboard in that window, the method onViewCreated() is selected on your own.

Photograph: link

If you press OK in this state, onViewCreated is added to the code by itself, and now you can call findViewById() through the top view of the fragment imported into getView().

I don't know what language you speak, so I prepared everything.

Java

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getView().findViewById(...);
}

Kotlin

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    getView().findViewById(...)
}

If this doesn't work, please let me know right away!


2022-09-20 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.