findViewById in Fragment findViewById in Fragment android android

findViewById in Fragment


Use getView() or the View parameter from implementing the onViewCreated method. It returns the root view for the fragment (the one returned by onCreateView() method). With this you can call findViewById().

@Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) {    ImageView imageView = (ImageView) getView().findViewById(R.id.foo);    // or  (ImageView) view.findViewById(R.id.foo); 

As getView() works only after onCreateView(), you can't use it inside onCreate() or onCreateView() methods of the fragment .


You need to inflate the Fragment's view and call findViewById() on the View it returns.

public View onCreateView(LayoutInflater inflater,                          ViewGroup container,                          Bundle savedInstanceState) {     View view = inflater.inflate(R.layout.testclassfragment, container, false);     ImageView imageView = (ImageView) view.findViewById(R.id.my_image);     return view;}


Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :

@Overridepublic void onViewCreated(View view, Bundle savedInstanceState) {    super.onViewCreated(view, savedInstanceState);    view.findViewById(R.id.yourId).setOnClickListener(this);    // or    getActivity().findViewById(R.id.yourId).setOnClickListener(this);}

Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method.It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.

Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully. i.e.

getView().findViewById("your view id");