본문 바로가기
ⓢⓣⓤⓓⓨ/ⓐⓝⓓⓡⓞⓘⓓⓢⓣⓤⓓⓘⓞ

[Kotlin] 리스트 뷰 (ListView)

by heaven00 2021. 8. 23.
728x90

 

 

 

 

출력 화면

 

 

 

리스트뷰 란?

사용자가 정의한 데이터 목록을 아이템 단위로 구성하여 화면에 출력하는 ViewGroup의 한 종류

ex) 전화번호부

 

 

 

 

리스트뷰 만드는 순서

 

(1) 리스트뷰가 들어갈 XML 레이아웃 정의

  - 리스트뷰에 들어갈 각 아이템의 레이아웃을 XML로 정의

    => 아래와 같이 리스트뷰가 들어갈 XML을 정의해주는 것이다.

 

 

 

 

 

(2) ListView에 각각의 데이터 항목을 표현하기 위한 레이아웃 정의

  - 리스트뷰에 들어갈 각 아이템을 하나의 뷰로 정의

     => 아래와 같이 리스트에 들어갈 아이템에 대한 디자인을 정의해주는 것이다.

 

 

 

 

 

(3) 모델 객체 정의

  - 리스트에 들어갈 데이터에 어떤 요소가 들어갈 것인지 정의해주는 것

ex) 위와 같은 형식으로 item을 만든다면, 프로필과 이름, 나이, 인사말의 요소가 들어갈 것이라는 큰 형태를 정의해주는 것

 

 

 

 

(4) 어뎁터 직접 생성

  - 어뎁터를 생성하고, 위에서 선언한 객체의 요소에 맞게 화면에 뿌려질 수 있도록 함

 

 

 

 

(5) 어뎁터와 리스트뷰 연결

  - MainActivity.kt 에서 연결해주면 된다.

 

 

 

 

 

 

위의 차례에 맞게 소스를 공유하면,

 

 

 

 

 

 

(1) 리스트뷰가 들어갈 XML 레이아웃 정의 (activity_main.xml)

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

 

 

 

 

(2) ListView에 각각의 데이터 항목을 표현하기 위한 레이아웃 정의 (list_item_user.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <ImageView
        android:id="@+id/iv_profile"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/android" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:text="이름"
        app:layout_constraintStart_toEndOf="@+id/iv_profile"
        app:layout_constraintTop_toTopOf="@+id/iv_profile" />

    <TextView
        android:id="@+id/tv_greet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="안녕하세요"
        app:layout_constraintBottom_toBottomOf="@+id/iv_profile"
        app:layout_constraintStart_toEndOf="@+id/iv_profile"
        app:layout_constraintTop_toBottomOf="@+id/tv_name" />

    <TextView
        android:id="@+id/tv_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="22"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_name" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

 

 

 

 

(3) 모델 객체 정의 (User.kt)

package com.example.myapplication

// 클래스 모델 객체
class User (val profile: Int, val name: String, val age: String, val greet:String)

 

 

 

 

 

 

 

(4) 어뎁터 직접 생성 (UserAapter.kt)

package com.example.myapplication

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

//User형태로 adpater에 담아라
class UserAdapter (val context: Context, val UserList: ArrayList<User>): BaseAdapter() {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view : View = LayoutInflater.from(context).inflate(R.layout.list_item_user, null)

        //id로 부터 view를 찾아라
        val profile = view.findViewById<ImageView>(R.id.iv_profile)
        val name = view.findViewById<TextView>(R.id.tv_name)
        val age = view.findViewById<TextView>(R.id.tv_age)
        val greet = view.findViewById<TextView>(R.id.tv_greet)

        val user = UserList[position]

        profile.setImageResource(user.profile)
        name.text= user.name
        age.text = user.age
        greet.text = user.greet

        return view
    }

    override fun getCount(): Int {
        return UserList.size

    }

    override fun getItem(position: Int): Any {
        return UserList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }


}

여기서 id를 통해 view를 찾는 부분에서 효율을 위해 복사 붙여넣기를 잘못하면 오류가 날 수 있는데

ImageView와 TextView를 잘 봐야한다. ImageView는 당연히 text로 불러올 수 없다.

 

 

 

 

 

(5) 어뎁터와 리스트뷰 연결 (MainActivity.kt)

package com.example.myapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import com.example.myapplication.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    //바인딩 객체 선언
    private var mBinding: ActivityMainBinding ?= null
    private val binding get() = mBinding!!
    
    
    //리스트 요소 순서에 맞게 선언
    var UserList = arrayListOf<User>(
        User(R.drawable.android, "이름", "22", "반갑습니다"),
        User(R.drawable.android, "이름1", "23", "안녕하세요"),
        User(R.drawable.android, "이름2", "24", "반갑습니다1"),
        User(R.drawable.android, "이름3", "25", "반갑습니다2"),
        User(R.drawable.android, "이름4", "26", "반갑습니다3"),
        User(R.drawable.android, "이름5", "27", "반갑습니다4"),
        User(R.drawable.android, "이름6", "28", "반갑습니다5")
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //setContentView(R.layout.activity_main)  --> 기존 setContenView 삭제

        //바인딩 초기화
        mBinding = ActivityMainBinding.inflate(layoutInflater)

        // 생성된 뷰 액티비티에 표시
       setContentView(binding.root)
        
        val Adapter = UserAdapter(this, UserList)
        binding.listView.adapter = Adapter
        
        
        //클릭한 리스트 이름 토스트메시지로 나타내기
        binding.listView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            val selectItem = parent.getItemAtPosition(position) as User
            Toast.makeText(this, selectItem.name, Toast.LENGTH_SHORT).show()
        }


        // 단순 하나의 모델
//        val item = arrayOf("사과", "배", "딸기", "키위", "메론")
//        binding.listView.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1,item)


    }

    override fun onDestroy() {
        mBinding = null
        super.onDestroy()
    }
}

 

 

 

주석한 부분은 하나의 요소로만 리스트뷰를 생성하고 싶을 때 저렇게 선언해주면 된다

실행시켰을 때 결과화면은 아래와 같다

 

 

 

 

 

 

 

 


 

 

위의 내용은 '홍드로이드' 님의 유튜브 강의를 보고 공부한 내용입니다.

코드를 변형한 부분도 있고 제가 이해한 방식대로 주석이나 추가 설명을 넣었습니다.

 

 

 

 

 

728x90

댓글