Saturday, May 30, 2015

How to reference xml elements using findViewById within fragment

While developing the Android application using activity, we use to reference the XML elements using findViewById method as below:

TextView name = (TextView) findViewById(;

This works only if we extend the class with Activity. It gives the compilation error as method not found if we extend the class with Fragment.

Though we are extending the class with the fragment, we can use the findViewById method with small modification. We need to get the rootview and in that view we can use this method as below

TextView name = (TextView) getView(). findViewById(;

This has to be used after inflating the xml. Also we can use the below way also:

myFragmentView = inflater.inflate(R.layout.MyLayout, container, false);
TextView name = (TextView) myFragmentView. findViewById(

Here I am using the TextView example. You can use this for any of the views. That's it. Hope this helps. Happy Coding.

No comments: