안드로이드의 기본으로 제공해 주는 NumberPicker을 사용하는데 기본 상태가 너무 못생겨 간단하게 손을 봐주었다.
결과물은 이러하다

NumberPicker에 사용할 백그라운드
drawable -> new -> drawable resource file에서 생성
gravity"center|fill_horizontal"적용 시 가운데 부분을 꽉 채울 수 있다.(대신 width부분은 의미가 없어짐)
가로넓이를 지정하고 싶다면 fill_horizontal을 지우고 width를 조절하면 된다.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:gravity="center|fill_horizontal">
<shape android:shape="rectangle">
<corners
android:radius="10dp"/>
<size
android:width="100dp"
android:height="40dp"/>
<solid android:color="@color/numberPickerColor" />
</shape>
</item>
</layer-list>
themes
themes에서 NumberPicker의 텍스트 크기, 스타일 등을 지정할 수 있다.
<style name="NumberPickerStyle">
<item name="android:textSize">18dp</item>
<item name="android:textStyle">bold</item>
</style>
xml
리니어 레이아웃으로 뷰를 가로로 배치할 수 있게 만들고 3개의 리니어 레이아웃을 만들어 weight을 1씩 주어 NumberPicker을 가운데 배치 시켰다.
그 외 만들어 놓은 background와 themes를 적용 android:selectionDividerHeight="0dp"로 해주면 거슬리는 NumberPicker의 작대기를 없앨 수 있다.
<androidx.appcompat.widget.LinearLayoutCompat
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="200dp">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
</androidx.appcompat.widget.LinearLayoutCompat>
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
<NumberPicker
android:background="@drawable/number_picker_background"
android:theme="@style/NumberPickerStyle"
android:selectionDividerHeight="0dp"
android:id="@+id/numberPicker"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.appcompat.widget.LinearLayoutCompat>
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
<TextView
android:text="년"
android:textStyle="bold"
android:textSize="18dp"
android:textColor="@color/base"
android:paddingRight="20dp"
android:gravity="left|center"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
main
NumberPicker에는 1900 ~ 2024의 숫자까지만 넣어 주었다.
it.toString()를 보면 값을 String 형태로 넣어 주고 있는데 NumberPicker는 외부적으로 String 형태의 값만 받아들인다고 한다.
val numberPicker: NumberPicker = view.findViewById(R.id.numberPicker)
val years: Array<String> = (1900..2024).map { it.toString() }.toTypedArray()
numberPicker.minValue = 0
numberPicker.maxValue = years.size - 1
numberPicker.displayedValues = years
'Android > 실습' 카테고리의 다른 글
| 안드로이드[코틀린] 이미지 밝기 조절 (0) | 2024.03.29 |
|---|---|
| 안드로이드[Kotlin] 여러 개의 버튼 처리 (0) | 2024.03.27 |
| 안드로이드[Kotlin] 버튼 클릭 시 background 색상 변경 (0) | 2024.03.26 |
| 안드로이드 Textview 특수 문자 사용 (0) | 2024.03.23 |
| [Kotlin] viewPager2, indicator (0) | 2023.12.21 |
댓글