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

안드로이드에서 수직 시크바(SeekBar) 구현하는 방법 – 단계별 완벽 가이드

이 튜토리얼에서는 안드로이드에서 실제로 동작하는 수직 시크바(Vertical SeekBar)를 구현하는 방법을 단계별로 살펴봅니다.

수직 시크바 구현 원리

안드로이드는 기본적으로 수평 방향의 SeekBar 위젯만 제공합니다. 하지만 android:rotation="270" 속성을 활용하면 기존의 수평 시크바를 270도 회전시켜 수직 형태로 손쉽게 사용할 수 있습니다. 별도의 커스텀 뷰나 외부 라이브러리 없이 적용할 수 있어 가장 간단한 방법으로 꼽힙니다.

구현 단계

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계 — 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. SeekBar에 rotation="270"을 지정하고, 진행 값을 표시할 TextView도 함께 배치합니다.

<?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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <SeekBar
      android:id="@+id/seekBar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:rotation="270"/>

   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:text=""
      android:textSize="16sp" />

</RelativeLayout>

3단계 — MainActivity 자바 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 예제에서는 최솟값(min)과 최댓값(max)을 직접 관리하며, 시크바의 값이 변경될 때마다 TextView에 현재 값이 갱신되도록 리스너를 등록합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

   SeekBar seekBar;
   TextView textView;
   int min = 0, max = 100, current = 50;

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

      textView = findViewById(R.id.textView);
      seekBar = findViewById(R.id.seekBar);
      seekBar.setProgress(max - min);
      seekBar.setProgress(current - min);
      textView.setText("" + current);

      seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
         @Override
         public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            current = progress + min;
            textView.setText("" + current);
         }

         @Override
         public void onStartTrackingTouch(SeekBar seekBar) { }

         @Override
         public void onStopTrackingTouch(SeekBar seekBar) { }
    });
   }
}

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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 실행(Run) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.

안드로이드에서 수직 시크바(SeekBar) 구현하는 방법 – 단계별 완벽 가이드

마무리

이처럼 rotation 속성만으로도 수직 시크바를 간편하게 구현할 수 있습니다. 음량 조절, 밝기 조절 등 세로 방향 슬라이더 UI가 필요한 경우 이 방법을 활용해 보세요. 더 정교한 터치 처리나 양방향 드래그가 필요하다면 커스텀 뷰를 직접 작성하거나 검증된 오픈소스 라이브러리를 사용하는 것도 좋은 대안입니다.