이 예제는 안드로이드 TextView에서 toUpperCase() 메서드를 사용해 텍스트를 대문자로 변환하는 방법을 단계별로 설명합니다.
1단계: 새 프로젝트 생성
Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력합니다.
2단계: 레이아웃 XML 작성
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, 그리고 변환을 실행할 Button이 배치되어 있습니다. 사용자가 버튼을 클릭하면 입력된 데이터를 가져와 대문자로 변환한 뒤 화면에 출력합니다.
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) {
String touppercase = name.getText().toString().toUpperCase();
text.setText(String.valueOf(touppercase));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}핵심 로직은 name.getText().toString().toUpperCase() 부분입니다. EditText에 입력된 문자열을 가져온 뒤 toUpperCase() 메서드를 호출하여 모든 알파벳을 대문자로 변환하고, 그 결과를 setText()로 TextView에 표시합니다. 만약 입력값이 비어 있다면 setError()를 통해 "이름을 입력하세요"라는 오류 메시지를 표시하도록 처리했습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 실행(Run) 아이콘을 클릭합니다. 이어서 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 나타납니다.

위 실행 결과에서 소문자로만 구성된 문자열 "krishna"를 입력하면, toUpperCase() 메서드에 의해 모두 대문자인 KRISHNA로 변환되어 화면에 출력되는 것을 확인할 수 있습니다.