9

I'm a beginner in App development for Android. My question is pretty simple. I can't seem to find out if the xml files in the layout folder should start with:

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

When i made a starter project, it wasn't there. But I'm also reading a book which says it should be there?

What is the correct way?

Haagenti
  • 7,974
  • 5
  • 38
  • 52

4 Answers4

9

Well this declaration should not be tagged with android but it is rather an xml syntax. It defines the XML version (1.0) and the encoding used (utf-8 = (8-bit Unicode Transformation Format)).

XML documents can contain non ASCII characters, like Norwegian æ ø å , or French ê è é.

To avoid errors,the XML encoding is specified,and files are saved Unicode.

These are some other examples of xml headers, that you can experiment with or study about :

<?xml version="1.0" encoding="us-ascii"?>
<?xml version="1.0" encoding="windows-1252"?>
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-16"?>
Prateek
  • 3,923
  • 6
  • 41
  • 79
5

This is called the "XML declaration" line. Technically it is optional, but it should be there, even if just for the benefit of text editors etc. that can use the encoding attribute when displaying the file.

If you look at any of the Android samples provided by Google or in fact, any of the internal layouts, they all begin with the XML declaration line.

See here for some examples: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/layout/

Alex MDC
  • 2,416
  • 1
  • 19
  • 17
  • 1
    To be more accurate, SOME of google's xml examples have this line. Plenty of auto-generated xml from templates in Android Studio do not contain this line. – SMBiggs May 04 '16 at 00:21
  • It's useless line noise. Get rid of it. – miguel Mar 23 '21 at 01:34
1

It's recommended you keep those tags at the start of your xml file. But in my experience, removing them made no difference...

Just ensure you have this present and it will work:

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

MyViewName could be LinearLayout FrameLayout RelativeLayout or even a View itself eg. ImageView, TextView... etc.

Which ever View or Layout you start with in the first line, you MUST have that url.

1

its not important to be there in xml.. its only the header of an xml file.. it indicate sthe xml version and encoding format

Ansar
  • 364
  • 3
  • 16