[kotlin] 선택기와 날짜 피커 구성을 위한 Material Components 사용 방법

안녕하세요! 이번에는 Kotlin과 Material Components를 사용하여 선택기와 날짜 피커를 구성하는 방법에 대해 알아보겠습니다. Material Components는 안드로이드 앱에서 친숙하고 아름다운 UI를 구축할 수 있도록 도와주는 라이브러리입니다. 선택기와 날짜 피커는 사용자가 간편하게 데이터를 입력할 수 있도록 도와줍니다.

선택기 구성하기

Material Components를 사용하여 선택기를 구성하는 방법은 매우 간단합니다.

  1. 의존성 추가: build.gradle 파일에 Material Components 라이브러리 의존성을 추가합니다.

     implementation 'com.google.android.material:material:1.4.0'
    
  2. 레이아웃 파일에서 선택기 추가: XML 레이아웃 파일에 선택기를 추가합니다.

     <com.google.android.material.textfield.TextInputLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:id="@+id/textInputLayout">
    
         <com.google.android.material.textfield.MaterialAutoCompleteTextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:id="@+id/autoCompleteTextView" />
     </com.google.android.material.textfield.TextInputLayout>
    
  3. 데이터 설정: 선택기에 표시할 데이터를 정의하고 연관된 어댑터를 설정합니다.

     val items = listOf("항목 1", "항목 2", "항목 3")
     val adapter = ArrayAdapter(this, R.layout.dropdown_menu_popup_item, items)
     autoCompleteTextView.setAdapter(adapter)
    

날짜 피커 구성하기

이번에는 Material Components를 사용하여 날짜 피커를 구성하는 방법을 살펴보겠습니다.

  1. 의존성 추가: 앞서와 마찬가지로 build.gradle 파일에 Material Components 라이브러리 의존성을 추가합니다.

  2. 날짜 피커 추가: XML 레이아웃 파일에 날짜 피커를 추가합니다.

     <com.google.android.material.textfield.TextInputLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:id="@+id/dateTextInputLayout">
    
         <com.google.android.material.textfield.TextInputEditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:id="@+id/dateTextInputEditText"
             android:hint="날짜를 선택하세요"
             android:focusable="false" />
     </com.google.android.material.textfield.TextInputLayout>
    
  3. 날짜 피커 다이얼로그 표시: 날짜 피커를 터치했을 때, 날짜를 선택할 수 있는 다이얼로그를 표시합니다.

     val dateTextInputEditText = findViewById<TextInputEditText>(R.id.dateTextInputEditText)
     val dateTextInputLayout = findViewById<TextInputLayout>(R.id.dateTextInputLayout)
     val dateSetListener = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
         // 선택한 날짜 처리
     }
     dateTextInputEditText.setOnClickListener {
         val calendar = Calendar.getInstance()
         val datePickerDialog = DatePickerDialog(
             this,
             dateSetListener, 
             calendar.get(Calendar.YEAR), 
             calendar.get(Calendar.MONTH), 
             calendar.get(Calendar.DAY_OF_MONTH)
         )
         datePickerDialog.show()
     }
    

Material Components를 사용하여 선택기와 날짜 피커를 구성하는 방법에 대해 간단히 알아보았습니다. 이제 여러분의 안드로이드 앱에서 사용자 친화적인 UI 구성에 Material Components를 적극적으로 활용해보시기 바랍니다.

더 많은 자세한 정보는 Material Components 공식 문서를 참고하시기 바랍니다.

감사합니다!