이 튜토리얼에서는 Android의 TextView와 함께 getChars() 메서드를 사용하는 방법을 단계별로 알아봅니다. getChars()는 문자열에서 특정 범위의 문자들을 추출하여 char 배열에 복사하는 유용한 메서드입니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성
다음 코드를 res/layout/activity_main.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout>
위 코드에서는 이름을 입력받기 위한 EditText, 클릭 버튼, 그리고 결과를 표시할 TextView를 배치했습니다. 사용자가 버튼을 클릭하면 입력된 데이터를 가져와 문자열의 9번째 위치부터 끝까지의 문자들을 반환합니다.
3단계: MainActivity 작성
다음 코드를 src/MainActivity.java에 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
char[] ch = new char[10];
name.getText().toString().getChars(9, name.getText().length(), ch, 0);
text.setText(String.valueOf(ch));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}getChars() 메서드 동작 원리
getChars() 메서드는 다음과 같은 매개변수를 사용합니다.
- srcBegin(9): 복사를 시작할 문자열의 시작 인덱스
- srcEnd(length): 복사를 종료할 문자열의 끝 인덱스
- dst(char[] ch): 문자가 복사될 대상 char 배열
- dstBegin(0): 대상 배열에서 데이터가 저장되기 시작할 위치
애플리케이션 실행하기
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 열고 툴바에서 Run 아이콘을 클릭하세요. 그런 다음 모바일 기기를 옵션으로 선택하면 기본 화면이 모바일 기기에 표시됩니다.

실행 결과 분석
위 결과에서 입력란에 tutorialspoint라는 문자열을 입력하면 “point”가 반환됩니다. 그 이유는 getChars()가 문자열의 9번째 위치부터 문자열 끝까지만 잘라내어 복사하기 때문입니다. 즉, “tutorialspoint”에서 인덱스 9에 해당하는 ‘p’부터 마지막 문자 ‘t’까지인 “point”만 char 배열에 저장되어 TextView에 출력되는 것입니다.