Meaning of R.layout.activity_main in android development (JAVA language)

后端 未结 5 1991
清酒与你
清酒与你 2020-12-31 09:25

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 t

5条回答
  •  佛祖请我去吃肉
    2020-12-31 09:57

    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:

    Application name
    

    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:

    
    

    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.

提交回复
热议问题