Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 특정 액티비티에만 테마를 적용하는 방법

이 튜토리얼에서는 안드로이드 앱에서 특정 액티비티(Activity)에만 테마(Theme)를 적용하는 방법을 단계별로 살펴봅니다. 일반적으로 테마는 AndroidManifest.xml의 <application> 태그에 지정해 앱 전체에 적용되지만, 개별 <activity> 태그에 android:theme 속성을 추가하면 해당 화면에만 별도의 스타일을 적용할 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    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!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

3단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

4단계: AndroidManifest.xml 수정 (핵심 단계)

테마를 특정 액티비티에만 적용하려면 androidManifest.xml에서 해당 <activity> 태그에 android:theme 속성을 지정하면 됩니다. 아래 코드를 참고하세요.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <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" android:theme="@style/Theme.AppCompat.Dialog.MinWidth">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

위 코드에서 애플리케이션 전체에는 기본 테마인 @style/AppTheme가 적용되고, MainActivity에는 @style/Theme.AppCompat.Dialog.MinWidth 테마가 별도로 지정되어 있습니다. 이렇게 설정하면 해당 액티비티만 대화상자(Dialog) 형태의 테마로 표시되며, 나머지 액티비티는 앱의 기본 테마를 그대로 유지합니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 모바일 기기를 선택하면, 기기 화면에 테마가 적용된 기본 화면이 아래와 같이 표시됩니다.

안드로이드에서 특정 액티비티에만 테마를 적용하는 방법