Open In App

XML Namespaces in Android

Last Updated : 31 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In an XML file, namespaces are used to provide elements and attributes with distinctive names. Names for elements or attributes in an XML instance may come from different XML vocabularies. The ambiguity between similar elements or attributes can be eliminated if each vocabulary is given its own namespace.

An identifier for a uniform resource is a namespace name (URI). The URI used for the namespace of a particular XML vocabulary often refers to a resource controlled by the author or entity. The namespace URI is merely handled as a string by an XML parser; the namespace specification neither mandates nor suggests that it be used to access data. For instance, there is no code in the actual document at “http://schemas.android.com/apk/res/android”. It just informs human readers about the android namespace. It is less likely that distinct namespaces would use the same identifier when using a URI, therefore we use URI  (like- “http://schemas.android.com/apk/res/android” instead of strings like -“android”)

An XML Namespace contains the following attributes:

  • Namespace: Namespace name represented as a URI to which the prefix is attached is known as the namespace URI. 
  • Prefix: XMLConstants are followed by a prefix, which is the part of the attribute name.

Let us see this with the example: 

XML Namespaces in Android

 

As we can see above the prefix  “android” is attached at the end of the namespace URI. If we create a new layout file in android, by default “xmlns:android=”http://schemas.android.com/apk/res/android” is written in the root layout. Keys should be defined in your XML since you will be referring to Android. Therefore, resources will associate the key with the namespace; for this reason, the namespace is defined in every Android XML file as: – “xmlns:android=”http://schemas.android.com/apk/res/android.” After defining it we can refer to the keys like we are referring to them in the example below

  • android:layout_width, 
  • android:layout_height, 
  • android:textColor, 
  • android:id,
  • android:layout_gravity,
  • android:text, and
  • android:textSize

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0F9D58"
        android:id="@+id/header"
        android:layout_gravity="center"
        android:text="My GFG App"/>
  
</LinearLayout>


If we remove the xmlns:android then we can’t define all these things.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads