Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is setContentView(R.layout.main)?

Tags:

android

layout

I understand that it has to do with the App layout, but when do I have to use it? I tried to look for a link that explained this method, but I couldn't find it. Thank you in advance!

like image 878
user3814312 Avatar asked Jul 11 '14 20:07

user3814312


People also ask

What is R layout Main?

layout. main - is an integer number implemented in nested layout class of R. java class file. At the run time device will pick up their layout based on the id given in setcontentview() method.

What is setContentView () method?

SetContentView(View) Set the activity content to an explicit view. SetContentView(Int32) Set the activity content from a layout resource. SetContentView(View, ViewGroup+LayoutParams)

What does setContentView R layout Activity_main do?

layout. activity_main ); This is a Java method called setContentView. It sets the XML file you want as your main layout when the app starts.

Why do we need to call setContentView () in onCreate () of activity class?

As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.


2 Answers

In Android the visual design is stored in XML files and each Activity is associated to a design.

setContentView(R.layout.main) 

R means Resource

layout means design

main is the xml you have created under res->layout->main.xml

Whenever you want to change the current look of an Activity or when you move from one Activity to another, the new Activity must have a design to show. We call setContentView in onCreate with the desired design as argument.

like image 87
Zare Ahmer Avatar answered Oct 04 '22 03:10

Zare Ahmer


As per the documentation :

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Your Launcher activity in the manifest first gets called and it set the layout view as specified in respective java files setContentView(R.layout.main);. Now this activity uses setContentView(R.layout.main) to set xml layout to that activity which will actually render as the UI of your activity.

like image 28
CodeWarrior Avatar answered Oct 04 '22 03:10

CodeWarrior