이 튜토리얼에서는 안드로이드 앱에서 setTheme() 메서드를 활용해 런타임에 현재 테마를 동적으로 변경하는 방법을 단계별로 살펴봅니다. 다크 모드 전환 등 다양한 UI 환경을 제공하고 싶을 때 유용하게 활용할 수 있는 기능입니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_centerInParent="true"/>
</RelativeLayout>3단계 — MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. 여기서 핵심 포인트는 setContentView()를 호출하기 전에 setTheme() 메서드로 원하는 테마를 지정해야 한다는 점입니다. 이 순서가 바뀌면 테마가 정상적으로 적용되지 않습니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_Black);
setContentView(R.layout.activity_main);
}
}4단계 — 매니페스트 설정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sampe">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 테마가 적용된 기본 화면이 아래와 같이 표시됩니다.
