What is the meaning of R.layout.activity_main ?
I understand that "." operator is used to define variables of a particular object but in this case its been used twice so I can't make anything out of it. Also what exactly is "R" and "layout"?
I mean obviously they are classes (right?) but what is their function ? Basically explain R.layout.activity_main !
Please comment if question too vague or too broad.
R.java
is a class (with inner classes, like layout
or string
) generated during the build process with references to your app's resources. Every resource you create (or which is provided by Android) is referenced by an integer in R
, called a resource id.
R.layout.*
references any layout resource you have created, usually in /res/layout
. So if you created an activity layout called activity_main.xml
, you can then use the reference in R.layout.activity_main
to access it. Many built-in functionality readily accepts such a resource id, for example setContentView(int layoutResid)
which you use during the creation of your activity and where you probably encountered this particular example.
If you create a string resource (in strings.xml) like this:
<string name="app_name">Application name</string>
it will get a new reference in R.string.app_name
. You can then use this everywhere where a string resource is accepted, for example the android:label
for your application in AndroidManifest.xml
, or on a TextView; either in the xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
/>
or in code: textview.setText(R.string.app_name)
.
You can access resources programmatically using the Resources
class, to which you can get a reference by calling getResources
on any context (like your activity). So for example you can get your app name described above in your activity by calling this.getResources().getString(R.string.app_name)
.
You can also supply different resources for different device properties/settings (like screen size or language), which you can access using the same references in R
. The easiest example here, imho, is strings: if you add a new values
folder in /res
with a language specifier (so /res/values-nl
for Dutch) and you add strings with the same identifier but a different translation and the resource management system cleverly figures out which one to provide for you based on your user's device.
I hope this helps a bit. For more information on resources see the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With