이 예제에서는 Kotlin을 사용하여 초기 기본 텍스트가 표시되는 Android 스피너(Spinner)를 만드는 방법을 알아봅니다. 스피너는 사용자가 목록에서 하나의 항목을 선택할 수 있도록 하는 드롭다운 UI 요소로, 안내 문구를 기본값으로 설정하면 사용자 경험을 크게 향상시킬 수 있습니다.
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:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Spinner Sample Program"
android:textColor="@android:color/background_dark"
android:textSize="16sp" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp">
</Spinner>
</LinearLayout>레이아웃은 수직 방향의 LinearLayout으로 구성되어 있으며, 상단에는 제목 역할을 하는 TextView, 그 아래에 항목 선택용 Spinner가 배치됩니다.
3단계: MainActivity.kt 작성
다음 코드를 src/MainActivity.kt에 추가합니다.
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var spinner: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
spinner = findViewById(R.id.spinner)
// 리스트 첫 번째 위치(인덱스 0)에 기본 안내 텍스트 추가
val footballPlayers: MutableList<String?> = ArrayList()
footballPlayers.add(0, "목록에서 선수를 선택하세요")
footballPlayers.add("크리스티아누 호날두")
footballPlayers.add("리오넬 메시")
footballPlayers.add("네이마르 주니오르")
footballPlayers.add("이스코")
footballPlayers.add("가레스 베일")
footballPlayers.add("루이스 수아레스")
val arrayAdapter: ArrayAdapter<String?> =
ArrayAdapter(this, android.R.layout.simple_list_item_1, footballPlayers)
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = arrayAdapter
spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View?,
position: Int,
id: Long
) {
if (parent.getItemAtPosition(position) == "목록에서 선수를 선택하세요") {
// 기본 안내 항목이 선택된 경우 아무 동작도 하지 않음
} else {
val item = parent.getItemAtPosition(position).toString()
Toast.makeText(parent.context, "선택됨: $item", Toast.LENGTH_SHORT).show()
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
}핵심 포인트: 이 코드의 핵심은 리스트의 인덱스 0번째 위치에 안내용 기본 텍스트("목록에서 선수를 선택하세요")를 먼저 삽입하는 것입니다. 이렇게 하면 스피너가 처음 화면에 표시될 때 해당 안내 문구가 기본값으로 나타나며, 사용자가 실제 항목을 선택했을 때만 onItemSelected() 콜백에서 토스트 메시지가 출력됩니다.
4단계: AndroidManifest.xml 확인
다음 코드를 androidManifest.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<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 모바일 기기가 컴퓨터와 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바에서
Run(실행) 아이콘을 클릭합니다. 실행 옵션에서 자신의 모바일 기기를 선택한 후, 모바일 기기 화면에서 결과를 확인합니다.
앱이 실행되면 스피너에 "목록에서 선수를 선택하세요"라는 기본 안내 텍스트가 표시됩니다. 스피너를 탭하면 축구 선수 목록이 드롭다운으로 나타나고, 항목을 선택하면 선택된 이름이 토스트 메시지로 표시됩니다.

