-
안드로이드 앱 개발 연습 - 3 | Spinner & RecyclerViewArchive/캡스톤디자인 2022. 3. 24. 18:39
Spinner
MainActivity.kt
class MainActivity : AppCompatActivity() { private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) val spinnerData = listOf<String>("First", "Second", "Third") val spinnerAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerData) binding.spinner.adapter = spinnerAdapter binding.spinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { binding.spinnerText.text = spinnerData[position] } override fun onNothingSelected(parent: AdapterView<*>?) {} } } }
RecyclerView
Memo.kt
data class Memo(var no: Int, var title: String, var timestamp: Long)
MainActivity.kt
class MainActivity : AppCompatActivity() { private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) val recyclerData: MutableList<Memo> = loadRecyclerData() var recyclerAdapter = CustomAdapter() recyclerAdapter.listData = recyclerData binding.recyclerView.adapter = recyclerAdapter binding.recyclerView.layoutManager = LinearLayoutManager(this) } fun loadRecyclerData(): MutableList<Memo> { val data: MutableList<Memo> = mutableListOf() for (no in 1..100) { val title = "This is Kotlin Android $no" val date = System.currentTimeMillis() var memo = Memo(no, title, date) data.add(memo) } return data } }
CustomAdapter.kt
class CustomAdapter: RecyclerView.Adapter<Holder>() { var listData = mutableListOf<Memo>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val binding = ItemRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false) return Holder(binding) } override fun onBindViewHolder(holder: Holder, position: Int) { val memo = listData.get(position) holder.setMemo(memo) } override fun getItemCount(): Int { return listData.size } } class Holder(val binding: ItemRecyclerBinding): RecyclerView.ViewHolder(binding.root) { init { binding.root.setOnClickListener { Toast.makeText(binding.root.context, "${binding.textTitle.text}", Toast.LENGTH_SHORT).show() } } fun setMemo(memo: Memo) { binding.textNo.text = "${memo.no}" binding.textTitle.text = memo.title binding.textDate.text = SimpleDateFormat("yyyy/MM/dd").format(memo.timestamp) } }
Holder에 사용하는 ItemRecyclerBinding은 어댑터에서 사용하는 레이아웃의 이름이 item_recycler이기 때문이다. 해당 레이아웃은 res >> layout에서 생성하여 recyclerView의 형태를 정의하는데 사용된다.