There's one thing that must be clarified here.
It's true that setContentView(R.layout.acivity_main2);
will link the layout file to your Activity. However, tools:context=".Main2Activity"
does not link your Activity to your layout file in the way you're thinking it does.
First, you need to take note of the word tools
in that line. tools
is the name typically used for the tools
namespace which provides a few xml attributes that only works during design-time. Take a look at this documentation: https://developer.android.com/studio/write/tool-attributes
Note how it said that when you're building your app, everything related to tools
will be stripped out. Therefore, tools:context=".Main2Activity"
plays zero role in linking your Activity to the layout.
Instead, it's only meant to link it during design, by allowing you to Preview your layout in a container that mimics the Activity you set in tools:context=
. So if you have a certain Theme for that Activity, the Preview will reflect the theme in the Preview Window.
On the other hand, setContentView(R.layout.activity_main2);
does play a major role in linking your xml layout to your Activity.
That statement is telling the Activity to inflate that xml layout and fetch all of it's Views and more. Essentially, by using setContentView(R.layout.activity_main2);
you're telling the Activity
that you want to use that layout file, so please create your layout using that file as the guidelines.
After you called setContentView(R.layout.activity_main2);
your Activity will know which layout you want to use, therefore making it possible to find the Views you want to work with through methods like findViewById()
. This wouldn't be possible if you never used setContentView()
.
Therefore, to answer your last two questions:
Switching Main2Activity to another Activity in your layout xml file will do nothing besides show you how your layout will look if it was placed inside the other Activity. It won't change the outcome of your app at all. All for designing purposes.
Switching to another layout file in setContentView()
will completely change the layout used in the Activity. Be careful of doing this, since if you have code used only for Views in the original layout, this WILL cause a crash if that code runs for the 2nd layout, because those Views don't exist anymore.
Bottomline is: