[kotlin] 안드로이드 스피너 ( Spinner ) 를 이용해 드롭다운 구현 및 커스텀

Leechaeyeon·2023년 11월 8일
0

코틀린 안드로이드

목록 보기
20/21

드롭다운

버튼을 클릭이나 터치 등의 상호작용을 통해 활성화했을 때, 보통 그 버튼의 아래로 하위 메뉴들이 펼쳐지는 요소

드롭다운 메뉴는 안드로이드에서는 스피너(Spinner) 를 이용해 구현할 수 있다.

먼저 메뉴의 목록이 될 레이아웃 구성

layout > item_spinner_home_register.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView_homeRegister_spinnerItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="아이템값"
        style="@style/Theme.Georgeois.Text"
        android:textSize="@dimen/font_size_18sp" />

</LinearLayout>

spinner의 백그라운드 구현

spinner_home_register_background

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <layer-list>
            <item>
                <shape android:shape="rectangle">
                    <solid android:color="#00FFFFFF"/>
                    <stroke android:color="@color/accentGray" android:width="1dp"/>
                    <padding
                        android:top="6dp"
                        android:bottom="6dp"
                        android:right="10dp"/>
                    <corners android:radius="8dp" />
                </shape>
            </item>

            <item
                android:drawable="@drawable/ic_arrow_drop_down"
                android:gravity="center|end"
                android:width="24dp"
                android:height="24dp" />
        </layer-list>
    </item>
</selector>

배경은 투명, 외곽선은 gray색상, icon은 어플의 주 색상을 사용하였다.

fragment_main.xml

<LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:layout_marginTop="@dimen/margin_8dp"
                    >
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="카테고리"
                        android:fontFamily="@font/space"
                        android:textSize="@dimen/font_size_18sp"
                        android:layout_marginRight="@dimen/margin_8dp"
                        android:layout_gravity="center"/>
                    <Spinner
                        android:id="@+id/spinner_homeRegister"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:background="@drawable/spinner_home_register_background"/>
                </LinearLayout>

CategorySpinnerAdapter Class

스피너의 어뎁터 클래스를 생성한다.

class CategorySpinnerAdapter(context: Context, @LayoutRes private val resId:Int, private val categoryList : List<String>):ArrayAdapter<String>(context,resId,categoryList){
    // 드롭다운하지 않은 상태의 Spinner 항목 뷰
    @SuppressLint("ViewHolder")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var itemSpinnerHomeRegisterBinding = ItemSpinnerHomeRegisterBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        itemSpinnerHomeRegisterBinding.textViewHomeRegisterSpinnerItem.text = categoryList[position]
        return itemSpinnerHomeRegisterBinding.root
    }

    // 드롭다운된 항목들 리스트의 뷰
    @SuppressLint("ViewHolder")
    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        var itemSpinnerHomeRegisterBinding = ItemSpinnerHomeRegisterBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        itemSpinnerHomeRegisterBinding.textViewHomeRegisterSpinnerItem.text = categoryList[position]
        return itemSpinnerHomeRegisterBinding.root
    }

    override fun getCount() = categoryList.size

}

여기서 itemSpinnerHomeRegisterBinding은 위에서 언급한
item_spinner_home_register.xml이 파일이 연결된 것이다.

MainFragment.kt

val outCategoryList = listOf(
        "운동",
        "책",
        "지출 카테고리3",
        "지출 카테고리4",
        "지출 카테고리5",
        "지출 카테고리6",
        "지출 카테고리7",
        "지출 카테고리8",
        "지출 카테고리9",
        "지출 카테고리10",
    )

임의로 리스트를 넣고

spinnerHomeRegister.adapter = CategorySpinnerAdapter(requireContext(),R.layout.item_spinner_home_register,outCategoryList)
            spinnerHomeRegister.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    val value = spinnerHomeRegister.getItemAtPosition(p2).toString()
                }
                override fun onNothingSelected(p0: AdapterView<*>?) {
                    // 선택되지 않은 경우
                }
            }

를 연결하면된다.

거르주아 프로젝트 도중에 까먹지 않기 위해서 작성했다.
참고하려면 링크 의 homeRegisterFragment.kt를 참고하면 된다.

✏️ 아직 수정중이므로 안나올수도 있고 코드가 변경될 수 있다.

0개의 댓글

관련 채용 정보