Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 스크롤 가능한 TextView 만드는 방법 (단계별 예제)

이 튜토리얼은 안드로이드 앱에서 스크롤 가능한(Scrollable) TextView를 만드는 방법을 단계별로 보여줍니다. 화면보다 긴 텍스트를 표시해야 할 때 TextView 자체에서 세로 스크롤이 되도록 설정하는 것이 핵심입니다.

구현 핵심 요약

스크롤 가능한 TextView는 사실 딱 두 가지만 설정하면 됩니다.

  • 레이아웃 XML의 TextView에 android:scrollbars="vertical" 속성 추가
  • Java 코드에서 textView.setMovementMethod(new ScrollingMovementMethod()) 호출

그럼 전체 과정을 하나씩 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택해 새 프로젝트를 만들고, 필요한 정보를 모두 입력합니다.

2단계 — 레이아웃 작성 (res/layout/activity_main.xml)

아래 코드를 activity_main.xml에 추가합니다. TextView에 android:scrollbars="vertical"이 선언된 부분에 주목하세요.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />
</RelativeLayout>

3단계 — MainActivity.java 작성

아래 코드를 MainActivity.java에 추가합니다. 샘플 텍스트는 마하트마 간디에 대한 소개글 발췌이며, 실제 개발 시에는 원하는 긴 문자열을 무엇이든 사용하면 됩니다.

package app.com.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.textView);

        // 스크롤을 확인하기 위한 긴 샘플 텍스트 (간디 소개글 발췌)
        String para = "Mohandas Karamchand Gandhi (1869–1948) was an Indian activist who led the Indian independence movement against British colonial rule. Employing nonviolent civil disobedience, he inspired civil rights movements across the world.\n\n"
            + "Born in coastal Gujarat and trained as a lawyer in London, Gandhi first practiced nonviolent resistance in South Africa. After returning to India in 1915, he organised peasants and labourers against excessive land-tax and discrimination.\n\n"
            + "He led the 400 km Dandi Salt March in 1930 and later called for Britain to quit India in 1942. He lived modestly, wore hand-spun traditional clothing, ate simple vegetarian food, and undertook long fasts as both self-purification and political protest.\n\n"
            + "Gandhi was assassinated by Nathuram Godse on 30 January 1948.";

        textView.setText(para);

        // 핵심: ScrollingMovementMethod를 설정해야 터치 스크롤이 동작합니다.
        textView.setMovementMethod(new ScrollingMovementMethod());
    }
}

여기서 가장 중요한 코드는 바로 이 한 줄입니다. 이 메서드를 호출하지 않으면 XML에서 scrollbars 속성을 설정했더라도 실제 터치 스크롤이 동작하지 않으니 반드시 함께 적용해야 합니다.

textView.setMovementMethod(new ScrollingMovementMethod());

4단계 — 매니페스트 확인 (androidManifest.xml)

AndroidManifest.xml은 프로젝트 생성 시 기본으로 만들어진 상태 그대로 사용하면 됩니다. 참고로 전체 코드는 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

5단계 — 앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 긴 텍스트가 채워진 TextView가 나타나고, 손가락으로 위아래로 밀어 내용을 자유롭게 스크롤할 수 있습니다.

안드로이드 앱에서 스크롤 가능한 TextView 만드는 방법 (단계별 예제)