While developing an Android application using an Activity, we typically reference XML elements with findViewById like this:
TextView name = (TextView) findViewById(R.id.Config_name);
This works when your class extends Activity, because Activity provides findViewById. When your class extends Fragment, calling findViewById directly on the Fragment will not compile — the method isn't available on Fragment.
How to reference views from a Fragment
You can still use findViewById from a Fragment, but you must call it on the fragment's root view (after the layout has been inflated). There are two common ways to do this:
1) Use getView() (after the view is created):
TextView name = (TextView) getView().findViewById(R.id.Config_name);
Note: getView() returns the Fragment's root view and is only non-null after the view has been created (for example, after onCreateView returns and typically in or after onViewCreated). Calling getView() too early can return null.
2) Use the view returned by inflater when you inflate the layout in onCreateView:
View myFragmentView = inflater.inflate(R.layout.MyLayout, container, false);
TextView name = (TextView) myFragmentView.findViewById(R.id.Config_name);
This approach is explicit and safe because you are using the view object you just inflated.
Minimal onCreateView example
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.MyLayout, container, false);
TextView name = (TextView) root.findViewById(R.id.Config_name);
// initialize other views here
return root;
}
Or, using onViewCreated (the view is already created and attached):
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView name = (TextView) view.findViewById(R.id.Config_name);
}
Notes and tips
- Always make sure you access views after the layout is inflated (onCreateView/onViewCreated) to avoid NullPointerExceptions.
- The examples above are Java; in Kotlin you can use view.findViewById
(R.id.Config_name) or prefer View Binding for safer, null-safe access. - Modern Android projects commonly use View Binding or Kotlin view binding delegates instead of manual findViewById — consider adding a View Binding example if you update this post later.
That's it. Use these patterns for TextView or any other view in your fragment. Hope this helps. Happy Coding.
No comments:
Post a Comment