Why inflate a Layout in Fragments instead of setting one already ready? Ex: setContentView (R.layout.activity_example)

1

I'm learning about Android and would like to better understand how this part of the system works.

Instead of inflating a layout, would not it be simpler to do as when creating an Activity, such as overwriting the onCreate method and setting up an XML layout?

Example:

public class SampleActivity extends AppCompatActivity {

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sample);
    }
}

Here is a part of the code of an example application that can be cloned from github: link

public class FridayFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_friday, container, false);
    }
}

Why is inflating necessary? What is his advantage? Thanks for any clarification.

    
asked by anonymous 25.01.2018 / 01:04

1 answer

2
The LayoutInflater is the class responsible for creating a View from an XML file, so you need it to instantiate and access a View .

In fragments, since onCreateView() requires a View return, you have to use LayoutInflater to create and return such View .

In Activity, you do not need to create View by using a LayoutInflater because the setContentView() method already does this internally, so it is only a practical way to create and assign a View to an Activity. If you look at the implementation of the setContentView() method of Activity, you will see that it also uses LayoutInflater .

@Override
    public void setContentView(int resId) {
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();

        // Cria a View baseada no id do layout passado e atribui a Activity
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }
    
25.01.2018 / 13:16