Created
June 5, 2023 18:05
-
-
Save truefedex/04cd28ac0be08fb845a294cdaedbd39f to your computer and use it in GitHub Desktop.
Good old ListView with reusable elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.mytestapplication | |
import android.app.ListActivity | |
import android.content.Context | |
import android.os.Bundle | |
import android.view.View | |
import android.view.ViewGroup | |
import android.widget.BaseAdapter | |
import android.widget.LinearLayout | |
import android.widget.TextView | |
class MainActivity : ListActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
listAdapter = TestAdapter(listOf( | |
Profile("John", 25), | |
Profile("Jane", 22), | |
Profile("Jack", 30) | |
)) | |
} | |
class Profile(val name: String, val age: Int) | |
class TestAdapter(val profiles: List<Profile>): BaseAdapter() { | |
override fun getCount(): Int { | |
return profiles.size | |
} | |
override fun getItem(position: Int): Any { | |
return profiles[position] | |
} | |
override fun getItemId(position: Int): Long { | |
return position.toLong() | |
} | |
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { | |
var view = convertView | |
if (view == null) { | |
view = ProfileView(parent!!.context) | |
} | |
(view as ProfileView).bind(profiles[position]) | |
return view | |
} | |
} | |
class ProfileView(context: Context): LinearLayout(context) { | |
val tvName: TextView | |
val tvAge: TextView | |
init { | |
tvName = TextView(context) | |
tvAge = TextView(context) | |
addView(tvName) | |
addView(tvAge) | |
} | |
fun bind(profile: Profile) { | |
tvName.text = profile.name | |
tvAge.text = profile.age.toString() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment