레이아웃 xml 파일에서 xmlns 코드의 의미는? ( xml에서의 import 기능 )

하이루·2022년 3월 30일
0

아래와 같이 레이아웃을 나타내는 xml 파일이 있다고 할때,

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/senderTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="NICKNAME" />

</androidx.constraintlayout.widget.ConstraintLayout>

이 부분은 무엇을 나타낼까?

<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
                         ......
>
                         ......

이 본론부터 말하자면 이 부분은 xml에서의 import 기능이라고 보면 된다.

즉, 해당 위치에 있는 라이브러리를 각각 임의의 변수에 담아서 사용하겠다는 의미이다.

  • 예를 들어,

    <androidx.constraintlayout.widget.ConstraintLayout 
       xmlns:android="http://schemas.android.com/apk/res/android"
                     ......
               >
     
       <TextView
           android:id="@+id/senderTextView"
    />
    • 우리가 위와 같이 TextView의 id 속성을 지정할 수 있는 것도, 뜯어보면
      "android"라는 변수에 "http://schemas.android.com/apk/res/android" 위치에 있는
      android 라이브러리를 지정하였고,
      id 속성을 가져와서 지정해주었기 때문이다.

    • 즉, 여기서 "android"라는 것은 라이브러리에 임시로 붙여준 변수명일 뿐 아무 의미 없다.

  • 단적으로 말해서 아래와 같이 해도 코드에는 아무 문제가 없다.

    <androidx.constraintlayout.widget.ConstraintLayout 
       xmlns:ThisIsAndroHaHa="http://schemas.android.com/apk/res/android"
                     ......
               >
     
       <TextView
           ThisIsAndroHaHa:id="@+id/senderTextView"
    />
    • 하지만 개발자간의 정해진 약속이 있기 때문에 위와 같이
      변수명을 변경하는 일은 사실상 없다고 보는 것이 좋다.

결론

  1. 우리가 레이아웃을 나타내는 xml파일에서 흔히 사용하는
    android, app, tools 등은
    문법이 아니라 변수명일 뿐이다.

    --> xml에서 tools를 써도 자동 import가 안되는 이유임

  2. xmlns는 import의 성격을 띄고 있으므로,
    xmlns에도 주목하여 각각의 라이브러리들의 성격을 인식하면
    좀 더 쉽게 코드를 파악할 수 있을 것이다.

profile
ㅎㅎ

0개의 댓글