How to get a list of all views in a fragment?

3.5k Views Asked by At

I would like to get a list of all views inside a main Fragment, so that I could iterate through them in a for loop. Maybe something like this:

for (View v : fragmentViews) {
2

There are 2 best solutions below

0
On BEST ANSWER

Ok, fragment has method getView() :

Get the root view for the fragment's layout (the one returned by {@link #onCreateView}), if provided. @return The fragment's root view, or null if it has no layout.

You can do this like:

    try {
        ViewGroup rootView = (ViewGroup) getView();
        int childViewCount = rootView.getChildCount();
        for (int i=0; i<childViewCount;i++){
            View workWithMe = rootView.getChildAt(i);
        }
    } catch (ClassCastException e){
        //Not a viewGroup here
    } catch (NullPointerException e){
        //Root view is null
    }
1
On

Inflate your fragment the usual way in your onCreateView:-

View rootView = inflater.inflate(R.layout.my_fragment, container, false);

To loop through views of your fragment:

ViewGroup container = (ViewGroup) rootView;
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
    View v = container.getChildAt(i);
    // perform action on this view
}