Programming/Android강의

안드로이드 강의11- Android TextView and string.xml(텍스트뷰 와 string.xml)

다중복이네 2015. 9. 16. 23:55


Android TextView and string.xml


오늘부터 안드로이드에서 사용하는 View들에 대해서 강의를 시작합니다.

이번 강의는 View중에서 가장 기본이 되는 View인 TextView에 대해서 알아보고 string.xml의 사용법을 알아보겠습니다.


TextView는 Button과 EditText의 부모 클래스로 안드로이드에서 Text를 표현해주는 기본 View입니다.

앞서서 Sample Code로도 많이 사용했고 사용하는데 크게 어려운 부분은 없습니다. 


오늘은 텍스트뷰와 함께 res/string.xml에 대해서도 함께 알아보겠습니다.



개발을 할 때는 뷰영역과 비지니스로직을 구분합니다. 그리고 안드로이드에선 뷰영역에서 좀더 세분화를 합니다.

큰틀인 layout와 layout에 사용될 resources 입니다.


string.xml은 문자열 resource를 나열해 놓은 xml입니다. 


resource를 따로 처리하는 이유는 관리의 용이성, 재사용가능, 언어별 문자열등의 기능을 위해서 입니다.

xml에 문자열이 고정되어 있으면 언어가 다른 두개의 국가를 지원해야 할경우 layout을 별도로 생성해 줘야 하지만 문자열을 strings.xml로 관리를 할경우는 해당언어별 strings.xml만 하나더 만들면 되기 때문에 관리하기가 용이합니다.


다시 본론으로 돌아가 textView를 만들고 버튼 클릭시 해당 TextView의 텍스트를 변경하는 것을 구현해 보겠습니다.


오늘 기본적으로 구현해 볼 레이아웃입니다.

텍스트가 구현되어 있으며 버튼을 누를경우 TextView의 텍스트를 변경하도록 기능을 구현해 보겠습니다.




xml코드를 보도록 할께요

<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/textViewText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:textColor="#FF0000"
        />

    <TextView
        android:id="@+id/textViewText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:textColor="#090909"
        />

    <TextView
        android:id="@+id/textViewText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:textColor="#0100FF"
        />

    <TextView
        android:id="@+id/textViewText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:textColor="#008299"
        />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_change_button"
        />

</LinearLayout>


위의 코드는 별 어려운 것은 없습니다. 단 text부분을 @string/xxxx 로 표현했는데요 이것은 string.xml에 있는 resource를 사용하겠다는 뜻입니다.


아래는 string.xml입니다. textView에 사용한 hello_world와, Button에 사용한 text_change_button의 문자열을 확인 할 수 있습니다.

<resources>
    <string name="app_name">Exam</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="text_change_button">텍스트변경</string>
</resources>


위의 코드에서 textSize는 dimens.xml로 textColor은 color.xml로 별도로 처리가 가능하지만 한꺼번에 다루기에 내용이 많을꺼 같아서 추후에 하나씩 다루도록 하겠습니다.


버튼을 클릭하면 아래와 같이 변경됩니다. 







자바 코드를 보면서 설명드리겠습니다.


package test.com.exam;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{

    private TextView textViewText1;
    private TextView textViewText2;
    private TextView textViewText3;
    private TextView textViewText4;
    private Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewText1 = (TextView) findViewById(R.id.textViewText1);
        textViewText2 = (TextView) findViewById(R.id.textViewText2);
        textViewText3 = (TextView) findViewById(R.id.textViewText3);
        textViewText4 = (TextView) findViewById(R.id.textViewText4);

        button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textViewText1.setText(getBaseContext().getText(R.string.app_name));
                textViewText2.setTextColor(Color.BLACK);
                textViewText3.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);


                SpannableStringBuilder builder = new SpannableStringBuilder(textViewText3.getText());
                builder.setSpan(new ForegroundColorSpan(Color.RED), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                builder.setSpan(new AbsoluteSizeSpan(30), 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                textViewText4.setText(builder);
            }
        });
    }
}


간단히 코드를 작성해 보았는데요 TextView의 메서드 중 많이 사용하는 메서드를 사용해 보았습니다.

setText : textView의 텍스트를 변경

setTextColor : textView의 색상을 변경

setTextSize : 텍스트 크기를 변경


위의 메서드는 설명이 필요 없을 정도로 간단한 메서드입니다. 다만 위의 코드는 Color.BLACK처럼 안드로이드의 기본적인 resource를 사용하였지만 개발시에는 모든 resource를 xml로 작성한 다음 해당resource를 사용하게 됩니다. resource에 접근하는 방법은 Context를 통해서 접근할 수 있습니다. Context에 대한 자세한 설명은 어느정도 강의가 진행 된 후 설명하겠습니다.


TextView의 가장 핵심은 Spannable인데요 Span은 HTML을 해보신 분들이라면 감이 잡힐겁니다. DIV와 SPAN의 차이는 DIV는 기본적으로 개행이 되지만 SPAN은 개행이 되지 않는다는 차이가 있습니다. 

즉 Spannable은 TextView의 텍스트를 영역을 나눈다고 보면 됩니다.


위에서는 setSpan메서드를 통해서 Color을 변경하고 두번째로 텍스트 Size를 변경하였습니다. 가운데 1,3은 시작과 끝 문자열 인덱스입니다.


이렇게 SpannableStringBuilder 을 작성하고 textView에 setText를 해주면 텍스트뷰 4번째와 같이 특정 영역만 바뀌게 됩니다.


Spannable은 검색을 할때 검색결과에서 검색어의 색상만 다르게 해야 할 경우 같은 부분적으로 텍스트를 변경해야 할 경우 사용하면 됩니다.