Hush 2022. 9. 4. 18:30

리스트뷰는 기본적으로 Adapter라는 것을 통해 데이터와 뷰를 연결한다.

우선 가장먼저 데이터 클래스를 원소로 갖는 코틀린 리스트로 데이터 뭉치를 구성한다.

이렇게 만든 코틀린 리스트를 Adapter에 인자로 전달한다.

 

리스트뷰를 만들 때 가장 집중해야 하는 곳은 Adapter의 구성이다.

arrayAdapter처럼 기본 제공하는 adapter를 사용해도 되고 직접 커스텀하여 사용해도 된다.

Adapter는 입력받은 데이터뭉치로 listView를 체워넣는 역할을 한다.

 

간단한 리스트뷰 생성

하나의 항목이 하나의 문자열로 이루어져있으며, 한번에 한 항목만을 선택할 수 있는 라디오 버튼을 제공하는 리스트뷰를 만들어 보았다.

<?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="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <EditText
        android:id="@+id/txt_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="추가" />

        <Button
            android:id="@+id/btn_modify"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="수정" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="삭제" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="초기화" />
    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


    </ListView>
</LinearLayout>
package com.hush.listviewcopy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        listView.choiceMode = ListView.CHOICE_MODE_SINGLE//한번에 하나만 선택 가능하게

        val items = ArrayList<String>()//데이터가 담길 배열
        //어댑터는 ArrayAdapter 사용
        val arrayAdapter = ArrayAdapter(
            this,
            android.R.layout.simple_list_item_single_choice,
            items
        )
        listView.adapter = arrayAdapter//Adapter 연결
        
        //textView에 선택한 항목 보이기
        listView.setOnItemClickListener { parent, view, position, id ->
            textView.text = listView.getItemAtPosition(position) as CharSequence
        }
        
        //항목 추가 기능
        btn_add.setOnClickListener {
            items.add(""+txt_input.text)
            arrayAdapter.notifyDataSetChanged()
        }
        
        //항목 수정 기능
        btn_modify.setOnClickListener {
            val check = listView.checkedItemPosition
            if(check > -1) {
                items[check] = "" + txt_input.text
                arrayAdapter.notifyDataSetChanged()
            }
        }

        //항목 삭제 기능. 버그 방지를 위해 clearChoices 함수가 사용되었음에 주목.
        btn_delete.setOnClickListener {
            val check = listView.checkedItemPosition
            if(check > -1) {
                items.removeAt(check)
                listView.clearChoices()
                arrayAdapter.notifyDataSetChanged()
            }
        }

        //항목 초기화 기능
        btn_reset.setOnClickListener {
            items.clear()
            arrayAdapter.notifyDataSetChanged()
        }
    }
}