Archives
Recent Posts
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Today
Total
관리 메뉴

안드로이드 개발자의 창고

[31일차 Android] ListView - SimpleAdapter 본문

Computer/Android

[31일차 Android] ListView - SimpleAdapter

Wise-99 2023. 6. 15. 11:59

 

 

 

출처 : 안드로이드 앱스쿨 2기 윤재성 강사님 수업 PPT

 

 

 

📖 SimpleAdapter

  • 개발자가 ListView의 항목을 자유롭게 디자인 했을 때 사용하는 Adapter Class
  • ListView의 항목 내에 배치된 View들을 직접 지정하면서 데이터를 설정할 수 있다.

 

 

 

예제 코드

row.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="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageViewRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textViewRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textAppearance="@style/TextAppearance.AppCompat.Large" />

        <TextView
            android:id="@+id/textViewRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textAppearance="@style/TextAppearance.AppCompat.Large" />
    </LinearLayout>
</LinearLayout>

 

 

 

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

    <TextView
        android:id="@+id/textViewMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <ListView
        android:id="@+id/listViewMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

 

 

 

MainActivity.kt

package com.test.android31_simpleadapter

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.SimpleAdapter
import com.test.android31_simpleadapter.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    lateinit var activityMainBinding: ActivityMainBinding

    // imageViewRow에 설정할 이미지 목록
    val imgData = arrayOf(
        R.drawable.imgflag1,
        R.drawable.imgflag2,
        R.drawable.imgflag3,
        R.drawable.imgflag4,
        R.drawable.imgflag5,
        R.drawable.imgflag6,
        R.drawable.imgflag7,
        R.drawable.imgflag8
    )

    // textViewRow1에 설정한 문자열 목록
    val textData1 = arrayOf(
        "토고", "프랑스", "스위스", "스페인", "일본", "독일", "브라질", "대한민국"
    )

    // textViewRow2에 설정한 문자열 목록
    val textData2 = arrayOf(
        "togo", "france", "swiss", "spain", "japan", "german", "brazil", "korea"
    )


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

        activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(activityMainBinding.root)

        activityMainBinding.run {
            listViewMain.run {
                val dataList = ArrayList<HashMap<String, Any>>()

                for (idx in 0 until imgData.size){
                    val map = HashMap<String, Any>()

                    map["img"] = imgData[idx]
                    map["data1"] = textData1[idx]
                    map["data2"] = textData2[idx]

                    dataList.add(map)
                }
                // HashMap에 데이터를 넣을 때 사용한 이름을 가지고 있는 배열
                val keys = arrayOf("img", "data1", "data2")
                // 데이터를 셋팅할 View의 ID 배열
                val ids = intArrayOf(R.id.imageViewRow, R.id.textViewRow1, R.id.textViewRow2)

                // SimpleAdapter를 생성한다.
                val simpleAdapter = SimpleAdapter(
                    this@MainActivity, dataList, R.layout.row, keys, ids
                )
            }
        }
    }
}

코드 리뷰

  • val dataList = ArrayList<HashMap<String, Any>>()
    • SimpleAdapter에 담을 데이터를 구성한다.
    • 데이터는 HashMap으로 구성하여 한 항목(Map)에 3가지(이미지, 한글명, 영문명)를 담는다.

 

  • for (idx in 0 until imgData.size){ ... }
    • val map = HashMap<string, any>()<string, any>
      • dataList에 들어갈 HashMap을 선언한다.
      • value로 String과 이미지가 들어가기 때문에 value를 Any 타입으로 설정한다.

 

  • val simpleAdapter = SimpleAdapter( ... )
    • SimpleAdapter에 설정하는 ArrayList 내의 HashMap의 개수 만큼 항목이 만들어진다.
    • 각 항목을 개별적으로 구성하여 보여준다.
    • 항목 하나를 구성하기 위해 항목 번째의 HashMap을 추출한다.
    • HashMap에 있는 데이터를 keys 배열에 들어있는 이름의 순서대로 추출한다.
    • ids 배열에 설정되어 있는 View의 ID 순서대로 데이터를 설정한다.

'Computer > Android' 카테고리의 다른 글

[32일차 Android] Spinner  (0) 2023.06.16
[32일차 Android] ListView - CustomAdapter  (0) 2023.06.15
[31일차 Android] ListView - ArrayAdapter  (0) 2023.06.14
[31일차 Android] FloatingActionButton  (0) 2023.06.14
[31일차 Android] CardView  (0) 2023.06.14