Is android:id specific to xml file or the whole project? - android

Is the android:id="#+id/somevalue" specific to the xml file in which it is defined, or the whole android project?
If it is project-wide, it seems like I have a lot of id's to come up for text fields. For example I have to name my "title" field like "title1" and "title2" etc...

They are unique on the whole project but can be used on different contexts. The reason is fairly simple: there will be just one R.id.name_of_id variable, though, they cannot be reference from anywhere. I mean, if you have and ID called #+id/my_id which is on the my_layout.xml file, you cannot use it unless you are currently working with my_layout.xml implicitly or explicitly. Implicity by using findViewById after a setContentView(R.layout.my_layout.xml) call (from the activity), or explicity by using it from an object (for instance, when you 'inflate' a layout and assign it to a View object you can do object.findViewById()).

Related

What is the relationship between XML and Java in Android?

In android, whats the difference between these 2? I started trying to make apps a few days ago and i can seem to wrap my head around it?
From what i have heard from the tutorial i am following, MaiActivity.java uses Java and Activity_main uses xml language?
Also is activity_main used to code the look of the app and MainActivity is used to code what the things do?
And what are ID's for? Is it just to reference certain buttons between the 2 files?
So basically from what i understand if what i have said above is correct, activity_main codes how the buttons look and gives them ID's, and MainActivity code what the buttons do and use the ID's to code the right button.
IS this correct?
From what i have heard from the tutorial i am following, MaiActivity.java uses Java and Activity_main uses xml language?
Also is activity_main used to code the look of the app and MainActivity is used to code what the things do?
Yes. Android uses xml to declare layouts and java to provide logic.
Note that while both activity_main and MainActivity follow common naming conventions, there is no need for them to be called this way.
And what are ID's for? Is it just to reference certain buttons between the 2 files?
IDs are used to identify views in all situations. The most common use case is in the respective java class.
When you create a android project 2 files get generated MainActivity(java) and activity_main(xml) , the xml file is used to create the views which you will be setting in the java file in the setContentView . The android build system created R.java file which contains your xml ids and other xml declaration . the java file can access the views in the xml by referring to R.id,R.string etc . basically its like a address of the xml view which you can refer from java . However I would recommend you to go through the android developer site - http://developer.android.com/guide/index.html
XML, it's an intermediate language between all programming languages and databases, used to pass values from language to another. All tags are user-defined as well as the properties inside such tags. The user can determine the name of the tag, and determine the properties in it, then the name of the tag and its properties with same names will be used in both languages, the first one sets the values to the properties while the other gets them. And so, it works as an intermediate language.
To be specific on how it works, for example, let's assume that we want to pass values from database to java class. There will be three files as follow:
- Java file (.class).
- XML file (.xml).
- Database file (.sql) for example.
In the XML file there is a tag:
<Student>
<name>the name of the student</name>
<age>number</age>
<collage>name</collage>
</Student>
Now each student's data will be in such tag, set from the database file (by an algorithm that writes inside a file when facing a specific text which is the property name), and the java file will get the values (by an algorithm that reads from a file when facing a specific text which is the property name). In this way the values are transformed from language to another.
In Android, the XML file contains all the elements of the activity such as buttons, text views, menus and so on. Each element has an XML tag with its name like Button tag, and each tag has properties. The java file will go to the XML file and look for element tag (Button tag) by the ID of that element (tag), and then the java file (class) takes the values of the properties and sets them to the variables (attributes) of the Button class, and then the Button class draws the Button in the activity. Furthermore, Android studio provides virtual mobile phone screen and displays on it the elements to tell the developer the primary appearance of the activity, in addition, to inform the developer what is the appropriate position, dimensions, or the color of the element, this will generate the XML code to make it easier while coding (it's called visual programming), but in fact the java file did not read the XML file yet, until the Gradle is building the APK (execution phase).
In Android basically we use two languages JAVA and XML.
XML
For layout, how your screen looks? What are the elements(Textview, Buttons, Listview, etc) on screen? What are the attributes of these elements (e.g What is the textcolour, background colour, visibility, font, width, height and much more?)?
The answer of all above question is inside layout subdirectory of res directory i.e a xml file.
Manifest.xml
You will find this xml in app directory of your project.
As in novel or any other book we have content/index page, which gives us the information about all chapters/topic included in that book. In a similar way APK have Manifest.xml which includes all information about Activities, User permissions, receiver, App name, App icon etc.
With the help of xml you can create animation (e.g how textview or any other element will be animated? fade in, fade out, zoom in zoom out etc). Also you can create shapes like circle(oval), rectangle etc and use them as a background or as a icon.
You can string.xml, color.xml etc
JAVA
Used for coding. This page control all the elements of xml with time. You can give default attributes values for different elements in xml, which will be used(for that particular element) in Activity(app) until you change that attribute in corresponding JAVA file for that particular element. To change attributes one must first define an id to the element and use that id in JAVA file to change its attributes.

How R.java file manage ID name declaed in XML layouts?

I was searching for difference in #id/ and #+id/ in our XML layouts. I got another question in my mind, Should we use different name for every component declared in layout for our application ?
I know that we can not declare two components with same name in a layout,
But if i talk about entire application. I use same name in other layouts.
Is this the correct way of coding ?
This answer quote that when we declare #+id/ there is new entry in R.java file, If i add same name component in other layout, Will it create other entry in R.java file ???
I am confused in this, and what is the right way of declaring names in XML layout.
Any help would be appreciated.
If you use #+id notation in multiple places, it will not create a new ID value each time it's used. The compiler will reuse the same ID for each of the same name in the same app.
You can use the #id notation when you know you are referencing an existing id. This is common when using relative layouts where you want to align some view with another view of some id in the same layout.
You should use the different name for each view in your application. And for difference for #id and #+id read the content in the following link you understand better Difference between "#id/" and "#+id/" in Android

Android naming convention

I am looking for a thorough Android naming convention suggestion.
I found a little bit here:
http://source.android.com/source/code-style.html#follow-field-naming-conventions
which says:
Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
Yet I am looking for something much more extensive covering all aspects of Android:
how to name layouts and views within,
how to name menus
how to name styles
how to name database tables (singular, plural) and fields within
etc
If there is some generally accepted suggestion I would just love to follow that. All SDKs seem to go their own way so I am particular interested in the Android way to do it.
ribot's Android Guidelines are a good example of standard naming conventions:
Naming convention for XML files:
activity_<ACTIVITY NAME>.xml - for all activities
dialog_<DIALOG NAME>.xml - for all custom dialogs
row_<LIST_NAME>.xml - for custom row for listview
fragment_<FRAGMENT_NAME>.xml - for all fragments
Naming convention for component/widget in xml files:
All components for X activity must start with the activity name
all component should have prefix or short name like btn for Button
For example,name for login activity component should be like following.
activity_login_btn_login
activity_login_et_username
activity_login_et_password
Short name of major components:
Button - btn
EditText - et
TextView - tv
ProgressBar - pb
Checkbox - chk
RadioButton - rb
ToggleButton - tb
Spinner - spn
Menu - mnu
ListView - lv
GalleryView - gv
LinearLayout -ll
RelativeLayout - rl
This is an excellent collection of best practices to start with:
https://github.com/futurice/android-best-practices
Here's what I use. I'll also copy from that link.
Object naming
Don't use the m or s prefix as per Google guidelines. I've stopped for years and I find it easier without them. The IDE will tell you when you're using something private or static; it seems like an obsolete convention.
CONSTANTS start with caps
Acronyms should only capitalize the first letter. For example, functionUrl and unitId. Not unitID.
Prefix with the type of object. For example a TextView which contains a name would be tvName. An EditView with a password would be etPass.
If it's something usually used only once in an activity (e.g. ListView), don't be afraid to just call it lv.
If it's not an object type just name it by it's function. For example, if it's a string that holds the ID, name it as id, not stringId. The IDE will tell you when it's a string or a float or a long.
Keep it legible. Use something like Pass instead of Password.
Within the XML, name should be underscore with no capitals, e.g. tv_name and et_pass
Put the android:id as the first attribute in the XML.
File naming
Prefix layouts with the type it is. E.g. fragment_contact_details.xml, view_primary_button.xml, activity_main.xml.
For the classes, categorize them into folders, but use suffixes. For example, /activities/MainActivity.java or /fragments/DeleteDialog.java. My folders are activities, fragments, adapters, models, and utils.
Adapters should say how and when they are used. So a ListView adapter for ChatActivity might be called ChatListAdapter.
colors.xml and dimens.xml as a pallete
For color, use names like gray_light, not button_foreground.
For dimens, use names like spacing_large, not button_upper_padding.
If you want to set something specific for your button color or padding, use a style file.
strings.xml
Name your strings with keys that resemble namespaces, and don't be afraid of repeating a value for two or more keys.
Use error.message.network, not network_error.
Reasoning
The purpose of naming conventions is not to make everything neat and consistent. It's there to flag possible mistakes and improve workflow. Most of these are designed to be convenient for keyboard shortcuts. Try to focus around minimizing bugs and improving workflow rather than looking nice.
Prefixes are great for those, "What's the name of that TextView?" moments.
Suffixes are there for the things which you don't access so often in that manner, but can be confusing. For example, I may not be sure whether I put my code in the Activity, Fragment, or Adapter of that page. They can be dropped if you like.
XML ids are often in lowercase and uses underscores just because everyone seems to do it this way.
CONSISTENCY
Everyone (unless working in teams) will have their own convention and which one you choose does not matter. Making sure it is consistent throughout the whole application does matter.
STRUCTURE
Personally, I use a naming convention like this as it runs from the class name down to component and is consistent throughout the xml:
CLASS: <ClassName>
ACTIVITY: <ClassName>**Activity**
LAYOUT: classname_activity
COMPONENT IDS: classname_activity_component_name
An example of this would be OrderActivity.class, order_activity.xml, order_activity_bn_cancel. Notice all the XML is in lowercase.
ABBREVIATING LAYOUTS
If you would like to use shorter names to keep the code tidier; then another method can be to abbreviate ALL the names in XML aswell as the layouts.
An example of this would be OrderActivity.class: ord_act.xml, ord_act_bt_can, ord_act_ti_nam, ord_act_tv_nam. I break down the names into three but this depends how many similar names you have
ABBREVIATING COMPONENT TYPES
When abbreviating component types try to keep these consistent too. I normally use two letters for the component type and three letters for the name. However sometimes the name will not be necessary if that is the only element of that type in the layout. The principle of the ID is to be unique
COMPONENT IDS: nam_act_component_nam
COMPONENT TYPE ABBREVIATIONS (This list shows two letters which is plenty)
Frame Layout: fl
Linear Layout: ll
Table Layout: tl
Table Row: tr
Grid Layout: gl
Relative Layout: rl
Text View: tv
Button: bt
Check Box: cb
Switch: sw
Toggle Button: tb
Image Button: ib
Image View: iv
Progress Bar: pb
Seek Bar: sb
Rating Bar: rb
Spinner: sp
WebView: wv
Edit Text: et
Radio Group: rg
List View: lv
Grid View: gv
Expandable List View: el
Scroll View: sv
Horizontal Scroll View: hs
Search View:* se
Tab Host: th
Video View: vv
Dialer Filter: df
Include: ic
Fragment: fr
Custom View (other): cv
I don't think there is a convention for this yet . each company has its own rules and I don't think anyone cares much about it here.
For me , I prefer putting the name to be bound to the context . for example , if there is an activity called "MainActivity" , its layout name would be "main_activity.xml" , and for each resource associated with this activity , I add a prefix "main_activity" so that I know that it uses it . same goes for the ids used for this activity .
The reason I use those naming is that it's easier to find them, delete if needed , and you won't get them replaced with others if you use android libraries since the names are quite unique.
I also try as much as possible to give meaningful names , so you will usually not see "listView" or "imageView2" as ids , but something like "contactsListView" and "contactImageView" . the same name (or similar) would also match the variables inside the java code, in order to make it easier to find.
So , in short, my tips are:
try to avoid numbers inside the names . they usually don't mean much , and show that you've only used drag&drop for the UI designer .
for demos, POCs and for questions here , don't worry yourself about naming .
try to add a prefix to all of the names of the resources (including ids) to show which context they belong to , and to achieve uniqueness.
give meaningful names wherever possible .
The newest Android Eclipse plugins create some of the files you mention automatically when you create a new project. From that, the naming is something like that:
layout/activity_main.xml
menu/activity_main.xml
...
I followed this scheme with e.g.
layout/fragment_a.xml
layout/fragment_b.xml
...
So it's something like with package names, from general to detailed. It also allows for neat sorting.
As to naming conventions and/or best practices, I often follow this md file of ribot/android-guidelines repository in github that has project and coding guidelines enlisted in it.
Every body uses his own, The main goal is to avoid mistakes and misinterpretation, specially when others read your code. Though syntax highlighting, and auto code inspection in modern IDE's makes it pretty point less.
But these naming conventions also make it very convenient when code completion is turned on. For example just type m and auto complete will show you a list of class fields.
But many times you have to work with other's code, which doesn't use such convention. such protected variables and overridden method parameters just add to the confusion.
Few examples:
Prefix class variables with m , and make static finals variables all caps, with _ separating words. Don't prefix any thing to lower scope variables.
Name layout after the UI parent, for example act_main.xml , frg_detail.xml , itm__act_main__list1.xml ; for an activity MainActivity, a fragment DetailFragment, item layout for a ListView in MainActivity with id list1, respectively.
Name element Id's in xml layouts like: lsv__act_main__list1 for a ListView and btn__act_main__submit for a `Button element. This makes them much easier to find with auto complete.

CheckedTextView Attributes ID and checkMark

Just start developing with android and think instead of reading a book a webinar could be better because a webinar could also teach me short ways and how an android developer thinks when writing the code but now got a problem
<CheckedTextView
android:id="#android:id/text1"
android:checkMark="?android:attr/listChoiseIndicatorMultiple"
</>
I dont understand the above code up to now see lots of different id definitions some of them was for resources and start with #resource/name, and some of those id definitions was like #+id/name just for creating a new id for the component but this time it is using android:id/text1 and I dont understand why it is using it in that manner
Besides, the checkMark thing make me confuse more what are all those ?android:attr/listChoiseIndicatorMultiple means?
Could you please explain me and show me some resource where can I find all those magic attributes so I can cope next time by myself and hope someday can answer other newbie questions
Thanks a lot in advance, and all comment will be appreciated.
Well, reading the docs has always been helpful to me:
Android Developer Site
XML Layout specific docs
#android:id/text1 is just a format used when the id has been previously defined. When you put a + in there that means the framework should create the resource id if it doesn't already exist.
It's normal to use #+id/thisid when defining a new view in a layout, and then use #id/thisid to reference the aforementioned view from another part of the layout (say, in a RelativeLayout where you need to tell one widget to be below another).
A question mark before the ID indicates that you want to access a style attribute that's defined in a style theme, rather than hard-coding the attribute.
#android:id/text1 basically this is used when you create any android component like button, layout, textviews etc.
but when you need any external component which is general for different platform like any color, image etc then you can declare it as #resource/name.
actually there is nothing different just keep one thing in mind that in #android:id/text1, id will simply work as an class name will contains other objects like textview, imageview or any other.
now if you declare #resource/name then in that also instead of id class name will be resource. actually when you will use it in java then these(#android:id/text1) will be converted into object hierarchy.

Android Resource ID

Must the resource ID's for views in XML layouts be unique across all layouts?
For example, I'm working on a little recipe manager app. I have a layout file for adding a new ingredient. In this layout I have an EditText for the ingredient that I'd like to call "edt_name". But I'm afraid that this name is too general; e.g. I might also have an EditText for a recipe name, a cooking procedure name, etc in other XML layout files.
However, I also don't want to make the labels more complex than necessary. I'd like to avoid calling the aforementioned EditText "edt_name_new_ingredient" if I could.
I'm curious as to how developers organize their resources in general. Android doesn't support sub-directories for resources as far as I know, so naming schemes can get really messy.
No, resource ID should not be unique across different xml layouts however they must be unique in a particular xml file.
Resource IDs are namespaced within the package. When you access a resource (in XML, for example), the package name is implicitly set to the current one. You can have other resource files in a different package and refer to those within your code or XML (this is how one accesses the platform resources that come with the SDK).
Similarly in code, you can access a different package's R class and use its resources, but all those within the same package must have unique names.
More info can be found in the documentation here.

Categories

Resources