Kotlin Adapter
From zen2
- Create a List View to display your items
- In a separate layout file create an item view
- Create a new file with Kotlin Class, call it XXXAdapter or whatever. eg
class CategoryAdapter(context:Context, categories:List<Category>): BaseAdapter() {}
You will have to override getView, getItem, getItemId, getCount
class CategoryAdapter(context:Context, categories:List<Category>): BaseAdapter() {
val context = context
val categories = categories
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val categoryView :View
categoryView = LayoutInflater.from(context).inflate(R.layout.category_list_item,null)
val resourceID = context.resources.getIdentifier(categories[position].image,"drawable",context.packageName)
categoryView.categoryImage.setImageResource(resourceID)
categoryView.categoryText.text = categories[position].title
return categoryView
}
override fun getItem(position: Int): Any {
return categories[position]
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getCount(): Int {
return categories.count()
}
}
Then in MainActivity or where you are calling this from:
class MainActivity : AppCompatActivity() {
lateinit var adapter:CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
adapter = CategoryAdapter(this,DataService.categories)
categoryListView.adapter = adapter
}
}
