Android - Resource

오픈소스 비즈니스 컨설팅
둘러보기로 가기 검색하러 가기

스마트폰 OS인 Android에서 Resource 관련 사항을 정리 한다.

Resource

Android에서 Resource 파일은 여러 종류가 있으며 개발 도구(Eclipse)에 의해 자동 컴파일되어 R.java 파일이 생성되어 관리 된다.

  • Resource 폴더
/res/~
  • Resource 변환
  • 디바이스의 구성, 시스템 언어 설정 등에 따라 리소스를 변환할 수 있다.
  • "리소스_파일-수식문자" 형태로 사용 한다.
  • 수식 문자의 종류
  • 참조: Providing Resources
  • 언어 : ISO 639-1에 정의된 2문자의 언어 코드
  • 국가 : r + ISO 3166-1-alpa-2에 정의된 국명 (예, rKR)
  • 화면의 방향 : port. 세로, land. 가로, square. 정방형 (default)
  • 화면의 해상도 : 92dpi, 108dpi
  • 터치스크린 : notouch. 없음, stylus. 터치팬, finger. 손가락
  • 내비게이션 : dpad. 십자키, trackball. 트랙볼, wheel. 호일
  • 키보드 상태 : keysexposed. 사용가, keyshidden. 격납상태
  • 입력 방법 : nokeys. 키 없음, qwerty. 쿼티 키보드, 12key. ten key
  • 화면 크기 : 두 변의 크기를 x 문자로 연결한 문자열, 긴 변을 먼저 정의함 (예, 640x480)

Resource에 접근 방법

  • XML 파일에서 attribute의 값으로 사용될 경우
attr="@[package:]클래스명/식별자"
예) attr="@string/app_name"
android:textColor="?android:테마에서_정의한_값"
  • XML 파일에서 새로운 Resource ID를 생성할 경우
android:id="@+id/식별자[:list]"
  • 다른 곳에서 이 Resource를 참조할 경우에는 다음과 같이 사용 한다.
@id/식별자
  • 안드로이드 식별자
@클래스명/식별자
@id/식별자

@+id/식별자
@+id/android:list    //--- ListView에서 사용 (list)
@+id/android:empty   //--- ListView에 값이 없을 경우 대신 표시 (empty)
  • Java 프로그램에서 사용될 경우
R.클래스명.식별자
예) R.string.app_name
  • Resources getResources() 사용
  • Activity에서 this.getResources()에서 Resources 객체를 가져 온다.
  • this.getResources().getString(R.string.msg_serach);
CharSequence getText(int id)
CharSequence[] getTextArray(int id)
String getString(int id)
String[] getStringArray(int id)
int[] getIntArray(int id)
TypedArray obtainTypedArray(int id)
float getDimension(int id)
int getDimensionPixelOffset(int id)
int getDimensionPixelSize(int id)
Drawable getDrawable(int id)
Movie getMovie(int id)
int getColor(int id)
ColorStateList getColorStateList(int id)
boolean getBoolean(int id)
int getInteger(int id)
XmlResourceParser getLayout(int id)
XmlResourceParser getAnimation(int id)
XmlResourceParser getXml(int id)
InputStream openRawResource(int id)
InputStream openRawResource(int id, TypedValue value)
AssetFileDescriptor openRawResourceFd(int id)
  • 시스템 Resource 사용
android.R.string.httpErrorBadUrl
@android:color/darker_gray

Anim Resource

  • 애니메이션을 관리하는 Resource
  • 저장 위치 : /res/anim/~.xml
  • 사용 태그 : <alpha>, <scale>, <translate>, <rotate>
  • 사용법
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.scaler));

Drawable Resource

  • 이미지를 관리하는 Resource
  • 저장 위치 : /res/drawable/이미지_파일
  • 사용 태그 :
  • 사용법
//--- Resource로부터 이미지 가져오기
setIcon(R.drawable.ic_menu);

Layout Resource

  • 화면 Layout과 View를 관리하는 Resource
  • 저장 위치 : /res/layout/~.xml, /res/layout-land/~.xml (가로 화면), /res/layout-port/~.xml (세로 화면)
  • 사용 태그
<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout>
    <TextView android:id="@+id/name_detail"
        android:layout_width="fill_parent"
        style="@style/intro_blurb"
    />
</RelativeLayout>

  • 사용법
public class zzTest extends Activity {
    private EditText location;

    public void onCreate(Bundle savedInstance) {
        //--- Resource로 Layout 설정
        //--- /res/layout/review_criteria.xml
        this.setContentView(R.layout.review_criteria);

        //--- Resource로부터 View (Widget) 정의
        this.location = (EditText) findViewById(R.id.name_detail);
    }
}

Menu Resource

  • 메뉴를 관리하는 Resource
  • 저장 위치 : /res/menu/~.xml
  • 사용 태그 : <menu>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/settingMenu"
        android:title="@string/settingMenu"
        android:icon="@drawable/icon"/>
    <item
        android:id="@+id/informationMenu"
        android:title="@string/informationMenu"
        android:icon="@drawable/icon"/>
</menu>

  • 사용법
  • ContextMenu menu 를 전달받은 경우
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.smartsearch_list_context, menu);
  • View의 ContextMenu를 표시하고 싶은 경우
openContextMenu(view);
  • 참고 문헌

Values Resource

  • 문자열, 컬러, 스타일, 영역, 배열을 관리하는 Resource
  • 저장 위치 : /res/values/~.xml

String

  • strings.xml : 문자열
<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <string name="string_name">string_value</string>
</resources>

R.string.string_name

Dimens

  • dimens.xml : 영역 (Dimensions)
<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <dimen name="dimen_name">dimen_value</dimen>
</resources>

Color

  • colors.xml : 색상
  • #RGB, #ARGB, #RRGGBB, #AARRGGBB
  • int color = getResource().getColor(R.color.~);
  • @color/~
<?xml version="1.0" encoding="utf-8" ?>
<resources>
    <color name="col_name">#color_value</color>
</resources>

Style, Theme

  • styles.xml : Style
  • parent를 통해서 상속
  • text.name : "."을 매개로 상위 style(text style)을 name이 상속

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <style name="text" parent="@android:style/Widget.TextView">
        <item name="android:textSize">22sp</item>
        <item name="android:layout_height">wrap_content</item>
    </style>
    <style name="text.name">
        <item name="android:layout_width">110dip</item>
        <item name="android:gravity">right|center_vertical</item>
        <item name="android:textColor">#3C5A98</item>
        <item name="android:paddingRight">10dip</item>
    </style>
    <style name="text.value">
        <item name="android:layout_width">200dip</item>
        <item name="android:gravity">left|center_vertical</item>
        <item name="android:textColor">#54788b</item>
    </style>
</resources>

  • layout에서 style 적용
style="@style/text.name"
  • AndroidManifest.xml에서 theme 적용
<application android:theme="@android:style/intro_burb" />
<activity    android:theme="@android:style/intro_burb" />
  • 참고 문헌

Array

  • arrays.xml : 배열
  • String[] ratings = getResource().getStringArray(R.array.ratings);
<?xml version="1.0" encoding="utf-8" ?>
<resources> 
    <array name="intro_burb">
        <item>~</item>
    </array>
</resource>

XML Resource

  • 컴파일된 XML 파일을 관리하는 Resource
  • 저장 위치 : /res/xml/~.xml
  • 사용 태그 :
  • 사용법
<people>
    <person firstname="~" lastname="~" />
</people>

XmlPullParser parser = this.getResources().getXML(R.raw.people);

while (parser.next() != XmlPullParser.END_DOCUMENT) {
    parser.getName() -> person
    parser.getAttributeCount() -> 2
    parser.getAttributeName(0) -> firstname
    parser.getAttributeValue(0) -> ~
}

Raw Resource

  • 임의의 파일을 관리하는 Resource
  • 저장 위치 : /res/raw/
  • 저장된 파일명은 "a~z 0~9 _ ."만 사용 가능함
  • "R.raw.이름"에서 이름은 확장자를 제외한 이름이 사용됨
  • 사용 태그 :
  • 사용법
byte[] buf = new byte[1024 + 1];
Resources resource = this.getResource();
InputStream finp = resource.openRawResource(R.raw.people);

while (finp.read(buf) != -1) {
    new String(buf);
}
finp.close();
  • Raw Resource에 저장된 파일을 InputStream이 아닌 파일로 받는 함수
  • /res/raw/에 있는 파일을 /sdcard/zztemp/ 폴더 아래에 복사한 후 해당 파일을 반환 한다.
  • /res/raw/에 있는 파일을 직접 반환할 수 있는 방법이 없기 때문에 이러한 방법을 사용 한다.
  • 권한 설정 : <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 호출 방법 : rawToFile(getResources().openRawResource(R.raw.raw명, "imsifile.apk");
   public static File rawToFile(InputStream finp, String filename) {
	FileOutputStream fout = null;
   	File tmpFile = null;
	byte[] buf = null;
	int cntRead = 0;

   	tmpFile = new File(Environment.getExternalStorageDirectory() + "/zztemp");
   	if (!tmpFile.exists()) {
   		tmpFile.mkdir();
   	}

		buf = new byte[1024 + 1];
		try {
			fout = new FileOutputStream(new File(tmpFile + "/" + filename));
			while (0 < (cntRead = finp.read(buf))) {
				fout.write(buf, 0, cntRead);
			}
		} catch (FileNotFoundException e1) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			try {
				if (fout != null) {
					fout.close();
				}
			} catch (Exception e) {
				fout = null;
			}
			try {
				if (finp != null) {
					finp.close();
				}
			} catch (Exception e) {
				finp = null;
			}
		}
   	return new File(tmpFile + "/" + filename);
   }

R.java 샘플

public final class R {
    public static final class attr {
    }
    public static final class color {
        public static final int mycolor=0x7f040000;
     }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int EditText01=0x7f060000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f050001;
        public static final int hello=0x7f050000;
    }
}

AAPT

  • AAPT : Android Asset Packaging Tool

참고 문헌