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

안드로이드 스피너(Spinner)에 초기 기본 텍스트 표시하는 방법 — 단계별 예제 가이드


안드로이드 스피너(Spinner)에 초기 기본 텍스트 표시하기

안드로이드 앱 개발에서 스피너(Spinner)는 사용자가 여러 옵션 중 하나를 선택하도록 할 때 가장 널리 사용되는 위젯입니다. 드롭다운 목록 형태로 동작하며, 탭하면 선택 가능한 항목들이 펼쳐집니다.

그런데 스피너는 기본적으로 목록의 첫 번째 항목이 곧바로 화면에 표시되기 때문에, "선택하세요"와 같은 안내 문구를 보여주려면 약간의 트릭이 필요합니다. 이번 예제에서는 리스트의 0번째 위치에 안내 문구를 삽입하여 초기 기본 텍스트처럼 보이게 만드는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 뒤, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다. 특별한 요구 사항이 없다면 Empty Activity 템플릿으로 진행하는 것이 가장 간편합니다.

2단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 수직 방향의 LinearLayout 안에 화면 제목 역할을 하는 TextView와 Spinner를 중앙 정렬로 배치했습니다.

<?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:id="@+id/linearLayout"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="스피너 샘플 프로그램"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:textSize="16sp"/>
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center">
    </Spinner>
</LinearLayout>

3단계 — MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. 핵심 포인트는 두 가지입니다.

  • 0번째 인덱스에 안내 문구 삽입: add(0, "목록에서 선수를 선택하세요")처럼 데이터 리스트의 맨 앞에 힌트 문구를 넣으면, 앱 실행 시 해당 문구가 스피너의 기본값으로 표시됩니다.
  • 선택 이벤트 분기 처리: onItemSelected() 콜백에서 안내 문구가 선택된 경우에는 아무 동작도 하지 않고, 실제 항목이 선택되었을 때만 토스트 메시지를 출력합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner = findViewById(R.id.spinner);
        List<String> footballPlayers = new ArrayList<>();
        footballPlayers.add(0, "목록에서 선수를 선택하세요");
        footballPlayers.add("Cristian Ronaldo");
        footballPlayers.add("Lionel Messi");
        footballPlayers.add("Neymar Jr");
        footballPlayers.add("Isco");
        footballPlayers.add("Gareth Bale");
        footballPlayers.add("Luis Suarez");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, footballPlayers);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (parent.getItemAtPosition(position).equals("목록에서 선수를 선택하세요")) {
            } else {
                String item = parent.getItemAtPosition(position).toString();
                Toast.makeText(parent.getContext(), "선택한 선수: " + item, Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
        });
    }
}

4단계 — AndroidManifest.xml 확인

androidManifest.xml에 아래 코드를 추가합니다. MainActivity가 LAUNCHER 인텐트 필터를 가지고 있어, 앱 실행 시 가장 먼저 열리는 시작 화면이 되도록 설정합니다.

<?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 ▶ 아이콘을 클릭하고 실행 기기로 본인의 모바일 기기를 선택합니다. 그러면 앱이 설치되면서 다음과 같은 기본 화면이 표시됩니다.

안드로이드 스피너(Spinner)에 초기 기본 텍스트 표시하는 방법 — 단계별 예제 가이드


안드로이드 스피너(Spinner)에 초기 기본 텍스트 표시하는 방법 — 단계별 예제 가이드

핵심 정리

안드로이드 스피너에 초기 기본 텍스트를 표시하는 핵심은, 어댑터에 전달할 데이터 리스트의 맨 앞(0번째)에 안내 문구를 추가하고, 선택 리스너에서 그 문구를 걸러내는 것입니다. 이 방법을 활용하면 별도의 커스텀 어댑터를 만들지 않고도 깔끔한 힌트 UI를 손쉽게 구현할 수 있습니다.