여러 개의 텍스트뷰를 초기화하기

참고 프로젝트: TextViewDemoC1

개발을 하다 보면 여러 개의 리소스를 찾아서 초기화하거나 특정 작업을 해야 할 필요가 있다. 그런 경우에 findViewById() 메소드를 사용해서 하나씩 리소스를 찾는 것은 매우 불편한 일이다. 이런 경우에 사용할 수 있는 방법이 바로 getIdentifier() 메소드를 사용하는 것이다. 이 메소드를 사용해서 여러 개의 리소스를 찾아서 초기화하는 방법을 살펴보겠다. 단, 이렇게 하기 위해서는 리소스 아이디가 일련된 값을 가지고 있어야 가능하다. 또는 아이디 값을 배열 등에 미리 설정해 놓은 경우에도 사용 가능하다.

레이아웃 XML에 세 개의 텍스트뷰를 추가하자.

코드 레이아웃 XML - /res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="none" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="none" />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="none" />

</LinearLayout>

레이아웃 XML에는 아이디가 textview로 시작하는 텍스트뷰가 세 개 존재한다. 이 아이디들은 모두 동일한 이름으로 시작하며, 마지막 숫자만 다르다. 이러한 텍스트뷰를 초기화하기 위해서는 아이디 값을 읽어올 수 있어야 한다. 바로 이때 사용할 수 있는 것이 getIdentifier() 메소드이다.

코드 Main.java

package com.androidside.textviewdemoc1;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        for (int i = 1; i < 4; i++) {
            int resID = getResources().getIdentifier("textview" + i, 
                                        "id", "com.androidside.textviewdemoc1");
            ((TextView) findViewById(resID)).setText("텍스트뷰 " + i);
        }
    }
}

getIdentifier() 메소드를 사용하면 특정 패키지 내의 리소스를 가지고 올 수 있다. 당연히 텍스트뷰만이 아니라 이미지 등 다른 자원들도 이 방법을 사용해서 가지고 올 수 있다. getIdentifier() 메소드는 다음처럼 두 가지 방식으로 사용할 수 있다.

첫 번째 방식은 첫 번째 인자에 리소스 이름만을 지정하고 두 번째와 세번 째에 리소스 타입과 패키지를 지정하는 방식이다. 두 번째 방식은 첫 번째 인자에 패키지, 리소스 타입, 리소스 이름을 모두 지정하는 방식이다. 타입에 id가 아닌 string이나 drawable를 지정하면 다른 리소스를 찾을 수 있다.

getResources().getIdentifier("textview"+i, "id", "com.androidside.textviewdemoc1");
getResources().getIdentifier("com.androidside.textviewdemoc1:id/textview"+i, null, null);

다음은 getIdentifier() 메소드를 정리한 것이다.

편주: 정리와 같은 형태인데, 노트나 돋보기 대신 API란 글자를 이용해 아이콘을 만들어주세요.
API android.content.res.Resources 클래스의 메소드

results matching ""

    No results matching ""