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

XML 값 파일을 활용해 배열에 R.drawable.* 형태의 드로어블 리소스 ID 저장하기

개요

이 튜토리얼에서는 Android의 XML 값(values) 파일을 사용하여 드로어블 리소스 ID를 R.drawable.* 형태로 배열에 저장하고, 자바 코드에서 이를 불러와 ImageView에 적용하는 방법을 단계별로 살펴봅니다.

1단계 — 새 프로젝트 만들기

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 이름, 패키지명, 최소 SDK 버전 등 생성에 필요한 모든 항목을 입력합니다.

2단계 — arrays.xml 작성

res/values/arrays.xml 파일을 생성하고 아래 코드를 추가합니다. 여기서는 세 개의 이미지 드로어블을 정수 배열(integer-array) 형태로 선언합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer-array name="random_images">
        <item>@drawable/image1</item>
        <item>@drawable/image2</item>
        <item>@drawable/image3</item>
    </integer-array>
</resources>

참고: @drawable/image1, image2, image3은 미리 res/drawable 폴더에 준비되어 있어야 합니다.

3단계 — 레이아웃 작성

res/layout/activity_main.xml에 다음 코드를 추가합니다. LinearLayout 안에 세 개의 ImageView를 세로 방향으로 배치합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/iv1"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="8dp"
        android:contentDescription="@string/app_name" />
    <ImageView
        android:id="@+id/iv2"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="8dp"
        android:contentDescription="@string/app_name" />
    <ImageView
        android:id="@+id/iv3"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="8dp"
        android:contentDescription="@string/app_name" />
</LinearLayout>

4단계 — MainActivity.java 작성

src/MainActivity.java에 다음 코드를 추가합니다. getResources().obtainTypedArray() 메서드로 XML에 정의한 배열을 가져온 뒤, getResourceId()를 호출해 각 인덱스에 해당하는 드로어블 ID를 얻어 ImageView에 설정합니다. 사용이 끝난 TypedArray는 반드시 recycle()로 해제해 주세요.

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
    ImageView iv1, iv2, iv3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv1 = findViewById(R.id.iv1);
        iv2 = findViewById(R.id.iv2);
        iv3 = findViewById(R.id.iv3);
        TypedArray images = getResources().obtainTypedArray(R.array.random_images);
        iv1.setImageResource(images.getResourceId(0, -1));
        iv2.setImageResource(images.getResourceId(1, -1));
        iv3.setImageResource(images.getResourceId(2, -1));
        images.recycle();
    }
}

5단계 — 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 아이콘을 클릭하세요. 기기 목록에서 본인의 모바일 기기를 선택하면, 아래 화면과 같이 배열에 담긴 세 개의 이미지가 각각의 ImageView에 표시됩니다.

XML 값 파일을 활용해 배열에 R.drawable.* 형태의 드로어블 리소스 ID 저장하기