Home / Mobile devlopment / Android(Java) / Finding Views FindViewById android

Finding Views FindViewById android

Finding Views FindViewById android

FindByID android

One the adapter is initialized let’s bind it to the ListView , but you may notice that we don’t have a reference to the ListView in our fragment, it was only defended in the layout XML.

The system takes and inflates layout XML files and turns them into a full view hierarchy with a root layout of the main activity at the very top of the view tree.

We can also assign IDs to each view in the tree ,but it’s not required if you don’t need a reference to an individual view.

For example if we have ImageView doesn’t have an ID associated with it and that’s okay.

Within the Java code of the associated activity of fragment if we need a reference to the button we can simply call findViewByID:


Button b = (Button)this.findViewById(R.id.btn);

Which will traverse down the view hierarchy until it finds a view with the ID button and then it will return that.

Similarly , we can traverse down the view hierarchy to find the linear layout with the ID container and then return that.


LinearLayout container = (LinerLayout)this.findViewById(R.id.container);

We could do the same to find a reference to TextView by traversing down the view hierarchy , but you’ll notice that we already have a reference to the container which is the direct parent of the TextView.

Hence , we can just call container findViewById to search subtree to find the TextView with this ID and then return it.


TextView t=(TextView)container.findViewById(R.id.txt);

With this method , we have a smaller sub-tree to search for a given view as opposed to searching the entire view hierarchy.

Unhandled error Team – with our love


Leave a Reply

Your email address will not be published. Required fields are marked *