When writing app in Android, we need two kind of files: activities and UI layouts. Activities are java files that tell what happens in the app. UI layouts are xml files that show how the app looks. Every activity is normally connected to one UI layout file. This connection is made with setContentView().
Typically setContentView() is in the beginning of onCreate() method in all activities. Normally it is the third line right after super.onCreate(savedInstanceState);
The format is the following:
setContentView(R.layout.layout_name)
The layout_name is the name of the file you want to use as a layout. Note that it is without .xml ending.
When creating a new activity in Android Studio, it automatically creates a new layout file for it at the same time. The layout files are in res/layout folder. Android Studio gives layout file the same name as activity name but reversed. For example MainActivity.java -> activity_main.xml.
The example below is the minimum app created in Android Studio with "Empty Activity" -option.
// Simple setContentView Example
package com.example.setcontentview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Line 2 defines the package name of the app.
Lines 4 and 5 show what libraries are imported into the code.
Line 7 is the class definition. This is the most typical way to do it.
Line 9 tells that we want to override the original onCreate method. There is already onCreate() method in AppCompatActivity.class but we don't want to use it. Instead, we use our own onCreate.
Line 10 is the definition for method onCreate(). Bundle savedInstanceState means that when we start this method, Android gives savedInstanceState to the method as a parameter. However, it is not needed in this example so we don’t care about it.
Line 11 is needed but it is always same so we don’t care about it here.
Line 12 tells that we want to use UI layout file activity_main.xml with this activity.