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

Android 앱에서 뷰(View)의 배경색을 설정하는 방법

이 튜토리얼에서는 Android 앱에서 뷰(View)의 배경색을 설정하는 방법을 단계별로 알아봅니다. XML 레이아웃에서 간단한 속성 하나만 추가하면 TextView를 비롯한 다양한 뷰의 배경색을 손쉽게 변경할 수 있습니다.

1단계: 새 프로젝트 생성

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

2단계: 레이아웃 파일 작성 (activity_main.xml)

아래 코드를 res/layout/activity_main.xml 파일에 추가합니다. 여기서 핵심은 TextView에 적용된 android:background 속성입니다. 원하는 색상의 헥스 코드(#046B5F)를 지정하면 해당 뷰의 배경색이 설정됩니다.

<?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="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:background="#046B5F"
        android:padding="16dp"
        android:text="My View Background color"
        android:textColor="#fff" />

</RelativeLayout>

3단계: MainActivity.java 작성

아래 코드를 src/MainActivity.java 파일에 추가합니다. 별도의 자바 코드 없이 XML만으로 배경색이 적용되므로 기본 액티비티 코드를 그대로 사용할 수 있습니다.

package app.com.sample;

import androidx.appcompat.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 파일에 추가합니다.

<?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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

애플리케이션 실행하기

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

Android 앱에서 뷰(View)의 배경색을 설정하는 방법

추가 팁

android:background 속성은 TextView뿐 아니라 Button, ImageView, LinearLayout 등 거의 모든 뷰에 동일하게 적용할 수 있습니다. 또한 헥스 코드 대신 @color/색상이름 형태로 colors.xml 리소스를 참조하면 색상을 일관성 있게 관리할 수 있습니다.