[Android/xml] margin, textSize, background 같은 반복되는 속성 쉽게 쓰기 style theme

라멘커비·2023년 9월 26일
0

TIL

목록 보기
17/17

안드로이드 UI 개발 중에 반복해서 쓰이는 속성들이 있을 것이다. 보통의 경우 애플리케이션의 전체적인 디자인을 헤치지 않도록 통일해서 디자인해야 한다. 때문에 Button, EditText와 같은 뷰를 디자인할 때 textSize, textStyle 등의 속성을 반복하게 된다. 이런 반복되는 속성을 묶어 하나의 style로 만들어 사용할 수 있다. 오늘은 속성을 묶어 하나의 style 속성으로 만들고 적용하는 방법을 알아보겠다.

style 만드는 방법


위 코드에서는 layout_margin, textSize, background 속성을 반복해서 사용하였다. 이 속성을 style로 묶어보겠다.

res > values > themes > themes.xml
themes.xml 파일로 이동해서 새로운 style 태그를 생성한다.

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- 어쩌구 기존 내용 -->
    <style name="AuthEditText" parent="android:Widget.EditText">
        <item name="android:textSize">20sp</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:layout_margin">10dp</item>
    </style>
</resources>

style 태그의 name은 개발자 마음대로 설정하면 된다. parent에는 속성을 사용할 위젯을 넣어준다. style태그 내에 item 태그로 속성을 묶어주면 된다.

style 적용 방법

사용할 때는 style = "@style/style name 지정명" 으로 명시하면 된다.

이렇게 하면 style을 사용하기 전과 동일하게 속성이 적용되는 모습을 볼 수 있다.

profile
일단 시작해보자

0개의 댓글