이 예제는 안드로이드에서 TextView에 표시된 텍스트의 문단(단락) 수를 계산하여 화면에 출력하는 방법을 보여줍니다.
구현 단계
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:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="100dp" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"> </TextView> </LinearLayout>
위 코드에서는 문단을 표시할 TextView를 배치했으며, 이후 Toast 메시지를 통해 문단 수에 대한 정보를 사용자에게 알려주게 됩니다.
3단계 − MainActivity.java 코드 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.");
String[] para = text.getText().toString().split("\r\n\r\n");
Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
}
}핵심 로직은 split("\r\n\r\n") 부분입니다. 텍스트를 빈 줄 두 개(캐리지 리턴 + 개행 문자가 연속으로 나오는 지점)를 기준으로 분할하면 각 조각이 하나의 문단이 되므로, 분할된 배열의 길이(para.length)가 곧 전체 문단 수가 됩니다. 이 값은 Toast 메시지로 화면에 표시됩니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 Run 아이콘을 클릭하세요. 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기의 기본 화면에 다음과 같은 결과가 표시됩니다.
