Skip to content

XML style rules

Bhaumik Soni edited this page May 15, 2017 · 1 revision

1 Use self closing tags

When an XML element doesn't have any contents, you must use self closing tags.

This is good:

<android.support.v7.widget.AppCompatTextView
	android:id="@+id/tv_profile"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content" />

This is bad :

<!-- Don\'t do this! -->
<android.support.v7.widget.AppCompatTextView
    android:id="@+id/tv_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</android.support.v7.widget.AppCompatTextView>

2 Resources naming

Resource IDs and names are written in lowercase_underscore.

2.1 ID naming

IDs should be prefixed with the name of the element in lowercase underscore. For example:

Element Prefix
TextView tv_
ImageView iv_
Button btn_
EditText et_
RecyclerView rv_

Image view example:

<ImageView
    android:id="@+id/iv_profile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Navigation Menu Item example:

<menu>
	<item
        android:id="@+id/nav_done"
        android:title="Done" />
</menu>

2.2 Strings

String names start with a prefix that identifies the section they belong to. For example registration_email_hint or registration_name_hint. If a string doesn't belong to any section, then you should follow the rules below:

Prefix Description
error_ An error message
msg_ A regular information message
title_ A title, i.e. a dialog title
action_ An action such as "Save" or "Create"

2.3 Styles and Themes

Unless the rest of resources, style names are written in UpperCamelCase.

3 Attributes ordering

As a general rule you should try to group similar attributes together. A good way of ordering the most common attributes is:

  1. View Id
  2. Style
  3. Layout width and layout height
  4. Other layout attributes, sorted alphabetically
  5. Remaining attributes, sorted alphabetically