Pr.Pg Next Pg

Setting ID tutorials

What is an ID

  • Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the view tree. 

  • IDs are basically used to access the elements in Java.

 

Creating an ID

  • ID is basically added by adding the attribute android:id.

  • This attribute is assigned with the string specifying the ID.

  • We take a complex example in which we add an ID to the Views created previously.

  • The basic syntax for creating an ID is android:id=”@+id/id_name” +id/id_name"ng an ID is in which we add an ID to the Views created previously.out.

ut.

agxel is a much efficient optio.

  • Here ‘@’ means reference as we have already mentioned before.

  • The ‘+’ sign is added which means that you are creating an ID, i.e, nothing but adding a resource name to the file R.java.

  • When we want to assign the name which is already defined in the Android namespace then we shouldn’t use the ‘+’ sign. For example android:id=”@android:id/list” which assigns the ID as list which has already been defined in the Android namespace.

  • For assigning the ID which you have already defined before in your own projects namespace you can just use the above syntax without the ‘+’ sign.

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:id="@+id/id_tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello"

android:textSize="40sp"

android:gravity="center"/>

 

<Button

android:id="@+id/id_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:layout_gravity="center"

android:gravity="center"/>

 

</LinearLayout>

 

 

  • In the above example, we have assigned ID to the TextView and to the Button.

  • We create a new ID for the TextView with the ‘+’ sign

  • In the second case we just assign the ID already defined before to the Button, hence no need of the ‘+’ sign.

  • Note : View IDs need not be unique throughout the tree, but it is good practice to ensure that they are at least unique within the part of the tree you are searching.

 

 

Pr.Pg border                                              Next Pg