findViewById returns NULL when using Fragment

前端 未结 7 1879
终归单人心
终归单人心 2020-12-14 16:15

I\'m new to Android developing and of course on Fragments.

I want to access the controls of my fragment in main activity but \'findViewById\' returns null. without f

7条回答
  •  执念已碎
    2020-12-14 17:03

    All the answers above tell you how you should "return the layout" but don't exactly tell you how to reference the layout that was returned so I was unable to use any of the solutions given. I used a different approach to solve the problem. In the Fragment class that handles the fragment, got to the onViewCreated() class and create a context variable in it that saves the context of the parent activity (main activity in my case).

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Context fragmentContext = (MainActivity) view.getContext();
    }
    

    Once that is done, you can use the new context to access items on your fragment from inside the onViewCreated() method.

    EditText editText = context.findViewById(R.id.textXML);
    

提交回复
热议问题