'TextView'에 해당되는 글 1건

  1. 2009.01.08 [Android/기초] GUI 컴포넌트의 색깔과 동작변경하기 ( TextView의 attribute, java method 사용 )

[Android/기초] GUI 컴포넌트의 색깔과 동작변경하기 ( TextView의 attribute, java method 사용 )

android/구글관련/한글 2009. 1. 8. 22:13
안드로이드는 각종 GUI 컴포넌트를 제공해 준다.
물론 다른 언어에서도 이러한 GUI 컴포넌트를 모두 제공해 준다. 자바에 비유하자면 JLabel, JButton, JTextArea등이 제공된다는것이다. 그렇다면 안드로이드에서는 이러한 GUI 컴포넌트들의 설정을 어떻게 할까? 그에 대해서 알아 보도록 하자.

기존 프로그래밍 언어(Java-Swing)에서는 어떻게 GUI 컴포넌트의 속성을 설정할까?
JLabel label = new JLabel();
label.setText("Hello");
label.setForeground(Color.red);

코드는 그냥 딱 읽으면 알 수 있도록 간단하다. 위의 소스에서는 label을 하나 만들고, 그 label이 가지게 될 문자열을 설정해주거나, 혹은 그 문자열의 색깔을 지정해 주게 된다. ( 물론 Java Beans를 이용해서 하는 방법도 있기는 하지만, 여기서는 생략하도록 한다. )


그렇다면 안드로이드에서는 어떻게 GUI 컴포넌트의 모양과 색깔을 바꿀 수 있을까?
안드로이드에서는 GUI 컴포넌트에 접근해서 각종 속성을 바꾸는 방법을 두가지 제공해 준다.
1. GUI의 정보가 들어 있는 XML파일을 수정해서 컴포넌트의 모양을 바꾸자. : XML의 attribute를 이용하는 방법
2. Java 소스 코드를 이용해서 GUI의 모양을 바꾸자. : java source에서 method를 호출하는 방법
그렇다면 각기 어떻게 모양을 바꿀 수 있는지 확인해 보도록 하자.

1. GUI정보가 들어 있는 XML파일을 수정해서 컴포넌트의 모양을 바꾸는 방법
근데 그 GUI 정보가 들어 있는 XML파일은 어디??
안드로이드에서는 각종 GUI 정보가 들어 있는 파일들이 있다. 위치는 프로젝트의 res/layout 폴더이다. 그중에서 이클립스를 이용해서 안드로이드 어플리케이션 프로젝트를 만들면 기본적으로 들어 있는 res/layout/main.xml 파일을 살펴 보자.
이 main.xml 파일은 안드로이드의 어플리케이션이 화면에 뜰때, 어떠한 모양(Layout)으로 뜰것인지를 정의해둔 XML 파일이다. 다른것은 다 모르니깐, 우리가 여기에서 관심을 가질만한 TextView Tag만을 확인해 보면 각종 attribute를 가지고 있는것을 볼 수 있다. ( android:layout_width, android:layout_height 등 ). 바로 저 attribute를 설정함에 따라서 각종 GUI의 형태를 변경 시킬 수 있게 되는것이다.

그렇다면 TextView에서 수정할 수 있는 attribute들은 무엇이 있는지, 어떤일을 하는지 어떻게 알수 있을까?
그런건 걱정하지 않아도 된다. 이미 안드로이드 사이트에 TextView가 어떤 attribute를 가질 수 있는지 모두 적혀 있으니 말이다.
우선 안드로이드 홈페이지에 접속하여, 상단 Bar에 있는 Docs 링크를 클릭한다. 그리고 좌측 Documentation 에서, Class Index ( http://code.google.com/intl/ko/android/reference/classes.html ) 를 누르면 모든 Class 목록들을 확인해 볼 수 있다. 우리가 궁금한것은 TextView이므로, TextView를 눌러서 API 문서를 확인해 보도록 하자.( http://code.google.com/intl/ko/android/reference/android/widget/TextView.html )

보다시피 Attribute name과 Related methods로 나눠지는것을 볼 수 있다. 여기서 Attribute name은 바로 XML 파일에서 수정할 때 사용되어지는 이름이다.

android:autoLink 속성은 이미지의 좌측에 설명되어 있듯이, url이나 email 주소 같은것들에다가 자동으로 클릭 가능하게 링크를 걸어 줄것이냐를 결정하는 속성이다. android:textColor 속성은 글자의 색깔을 변경해주는 attribute이다. 이 두개의 attribute를 사용법을 알기 위해서는 해당 attribute link를 클릭하여 API 문서를 확인해 보도록 하자.
android:autoLink : http://code.google.com/intl/ko/android/reference/android/widget/TextView.html#attr_android:autoLink

android:autoLink

Controls whether links such as urls and email addresses are automatically found and converted to clickable links. The default value is "none", disabling this feature.

Must be one or more (separated by '|') of the following constant values.

Constant Value Description
none 0x00 Match no patterns (default)
web 0x01 Match Web URLs
email 0x02 Match email addresses
phone 0x04 Match phone numbers
map 0x08 Match map addresses
all 0x0f Match all patterns (equivalent to web|email|phone|map)

This corresponds to the global attribute resource symbol autoLink.


android:textColor : http://code.google.com/intl/ko/android/reference/android/widget/TextView.html#attr_android:textColor

android:textColor

Text color.

May be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

This corresponds to the global attribute resource symbol textColor.


위의 attribute에 대한 설명을 대략 읽어 보고 main.xml에서 TextView 파일을 아래와 같이 수정해 보자.
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:autoLink="web|email"
    android:textColor="#FF0000"
    />


/res/values/strings.xml파일을 열어서 hello 부분을 수정하여 email주소와 URL주소를 넣어 주도록 하자.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, email : master@gcodebank.com, visit : http://gcodebank.com</string>
    <string name="app_name">AppName</string>
</resources>


그런뒤에 이클립스에서 우리가 고친 프로그램을 실행해서 확인해 보면, 원하는대로 글자를 빨간색으로, 그리고 email과 URL주소는 자동으로 링크가 걸린 형태로 나타남을 알 수 있다.
이로써 XML attribute를 이용하여 GUI 컴포넌트의 모양을 바꾸는 법을 알 게 되었다.


2. Java 소스 코드를 이용해서 GUI의 모양을 바꿀 수도 있다.
( 우선 main.xml을 원래대로 돌려 놓도록 하자. - main.xml에서 android:autoLink와 android:textColor을 제거 )

응? TextView에서 어떤것을 바꿀 수 있고, 그걸 보려면 어디로 가냐구??
이전처럼 TextView의 API 문서를 보자 ( http://code.google.com/intl/ko/android/reference/android/widget/TextView.html )
그리고 Related methods 부분에 있는 setAutoLinkMask(int)와 setTextColor(ColorStateList) 부분을 클릭하여 해당 메소드를 어떻게 사용하는지 확인해 보도록 하자.
setAutoLinkMask(int) : http://code.google.com/intl/ko/android/reference/android/widget/TextView.html#setAutoLinkMask(int)

public final void setAutoLinkMask(int mask)

Sets the autolink mask of the text. See Linkify.ALL and peers for possible values.

Related XML Attributes

Linkify.ALL을 보라고 하는데, 이를 알아 보도록 하자.( 핵심적인 일부만 여기에 옮겨 둔다. )
Linkify : http://code.google.com/intl/ko/android/reference/android/text/util/Linkify.html#ALL

ALL  Bit mask indicating that all available patterns should be matched in methods that take an options mask  
EMAIL_ADDRESSES  Bit field indicating that email addresses should be matched in methods that take an options mask  
MAP_ADDRESSES  Bit field indicating that phone numbers should be matched in methods that take an options mask  
PHONE_NUMBERS  Bit field indicating that phone numbers should be matched in methods that take an options mask  
WEB_URLS  Bit field indicating that web URLs should be matched in methods that take an options mask

setTextColor(ColorStateList) : http://code.google.com/intl/ko/android/reference/android/widget/TextView.html#setTextColor(android.content.res.ColorStateList)

public void setTextColor(ColorStateList colors)

Sets the text color.

Related XML Attributes

setTextColor을 사용하기 위해서 param으로 ColorStateList를 넣어야 하니깐 그것도 알아 보자.

ColorStateList : http://code.google.com/intl/ko/android/reference/android/content/res/ColorStateList.html
이 클래스는 조금 특이한데, 쉽게 색을 정하기 위해서 valueOf라는 메소드를 사용하도록 하자.

public static ColorStateList valueOf(int color)

Creates or retrieves a ColorStateList that always returns a single color.

위와 같이 각 메소드의 사용법을 알았으니, 이제 Java소스를 수정하여 autoLink와 textColor이 변경되도록 만들어 보자.
이때 Layout을 설정해 놓은 res/layout/main.xml 파일을 살짝 수정해 준다. 아래의 소스를 보다시피 id를 추가해 주는것이다.
지금 우리는 Java 소스코드에서 TextView의 모양을 바꾸려고 한다. TextView의 모양을 바꾸려면 main.xml 파일에서 어떤 GUI 컴포넌트가 수정하고자하는 TextView인지를 알 수 있어야 한다. 이를 위해서 TextView에 id를 하나 설정해 주어, 이를 구분할 수 있게 해 준다. 설정해둔 id를 이용해서 Java 소스에서 이를 불러다 쓸 수 있다. ( 추가적으로 setText메소드도 테스트하기 위해서, android:text attribute도 제거해 두었다. )
<TextView  
	android:id="@+id/testTextView"
	android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    />


위와 같이 파일을 고치면 R.java 파일이 자동으로 업데이트 되면서 R.id.testTextView로 접근할 수 있도록 변경된다.
public final class R {
    // 생략...
    public static final class id {
        public static final int testTextView=0x7f050000;
    }
    // 생략...
}


이제 R.id.testTextView라는 것으로 이전에 설정해 두었던 TextView에 접근할 수 있게 되었다. 이때 접근하는 방법은 findViewById(int)라는 메소드를 사용하는데, 자세한 설명은 집어 치우고 그냥 바로 아래의 소스코드를 확인해 보자.
package com.ggaman.android.sample;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.util.Linkify;
import android.widget.TextView;

public class Test extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // main.xml에서 testTextView라고 id를 설정해둔 TextView를 가지고 온다.
        TextView tv = (TextView)findViewById(R.id.testTextView);
        
        // autoLink에 대한 설정을 해 준다.
        tv.setAutoLinkMask(Linkify.WEB_URLS);
        
        // TextView의 textColor을 설정해 준다. ( ARGB 값을 준다. )
        tv.setTextColor(ColorStateList.valueOf(0xFFFF0000));
        
        // TextView에 나타날 글자도 설정해 준다.
        tv.setText("Hello email : master@gcodebank.com visit : http://gcodebank.com");
    }
}


위와 같이 TextView를 얻어오고, autoLink와 textColor, 그리고 text 까지 설정을 마쳤다. 위의 코드를 수행한 결과는 아래와 같이 수행됨을 볼 수 있다. ( 첫번째 attribute와 결과가 다른데, 이는 autoLink를 email에는 주지 않았기 때문에 다른것이다. - java 소스를 잘 확인해 보기 바란다. )

이로써 TextView 같은 GUI 컴포넌트의 정보를 바꿀 수 있는 두 가지 방법을 모두 알아 보았다.

: