본문 바로가기

Mobile/Android

[Android / Kotlin] 강좌2 - custom list 만들기


[Android / Kotlin] 강좌2 - custom list 만들기


어댑터 패키지 생성

1public class CategoryAdapter: BaseAdapter() {
2
3}

그 안에 categorAdapter 클래스를 생성후 baseAdapter를 상속받아준다.

base 어댑터는 커스텀 리스트 어댑터를 만들때 상속받아 사용한다.

1package sorisoft.co.kr.shoppingmall.Adapters
2
3import android.content.Context
4import android.view.LayoutInflater
5import android.view.View
6import android.view.ViewGroup
7import android.widget.BaseAdapter
8import android.widget.ImageView
9import android.widget.TextView
10import sorisoft.co.kr.shoppingmall.Model.Category
11import sorisoft.co.kr.shoppingmall.R
12
13/**
14 * Created by harry on 2017. 9. 28..
15 */
16
17
18/* adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1,DataService.categories)
19 * Adapter CategoryAdapter this DataService.categories */
20
21class CategoryAdapter(context: Context, categories: List<Category>) : BaseAdapter(){
22
23 val context = context
24 val categories = categories
25
26 override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
27 val categoryView: View
28
29 //xml
30 categoryView = LayoutInflater.from(context).inflate(R.layout.category_list_item, null)
31
32 //
33 val categoryImage : ImageView = categoryView.findViewById(R.id.categoryImage) // category_list.item.xml id categoryImage
34 val categoryName: TextView = categoryView.findViewById(R.id.categoryName)
35
36 //
37 val category = categories[position]
38
39 //
40 categoryName.text = category.title
41 val resourceId = context.resources.getIdentifier(category.image, "drawble", context.packageName) // , , ( )
42 categoryImage.setImageResource(resourceId) //
43
44 return categoryView
45 }
46
47 override fun getItem(position: Int): Any {
48 //
49 return categories[position]
50 }
51
52 override fun getItemId(position: Int): Long {
53 // id
54 return 0
55 }
56
57 override fun getCount(): Int {
58 // ios numberOfSection
59 return categories.count()
60 }
61
62}

이제 커스텀 리스트를 만들었으니 실제 mainactivity와 연동하여준다.

1class MainActivity : AppCompatActivity() {
2
3 lateinit var adapter: ArrayAdapter<Category>
4
5 //
6 adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1,DataService.categories)
7

위 부분을

1class MainActivity : AppCompatActivity() {
2
3 lateinit var adapter: CategoryAdapter
4
5 //
6
7 adapter = CategoryAdapter(this,DataService.categories)
8

우리가 만든 CategoryAdapter로 바꾸어준다.

1<ListView
2 android:id="@+id/categoryListView"
3 <-- -->
4
5 -->
6 android:divier="@null"
7 />

위 코드를 추가하여 divier를 없애주자