RUslan159

Untitled

Sep 20th, 2021
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. class DiffAdapter(private val item: Item) :
  2. ListAdapter<Pair<String, Double>, DiffViewHolder>(MyDiff()) {
  3.  
  4. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = DiffViewHolder(
  5. LayoutInflater.from(parent.context).inflate(R.layout.item_converter, parent, false)
  6. )
  7.  
  8. override fun onBindViewHolder(holder: DiffViewHolder, position: Int) {
  9. val measure = item.measures[position]
  10.  
  11. holder.onBind(measure.first, item.value * measure.second, object : TextWatcher {
  12. override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
  13.  
  14. }
  15.  
  16. override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
  17. item.value = s.toString().toDouble() / measure.second
  18. holder.itemView.post { notifyDataSetChanged() }
  19. }
  20.  
  21. override fun afterTextChanged(s: Editable?) {
  22. }
  23. }) { v, hasFocus ->
  24. if (hasFocus) {
  25. item.measures.add(0, item.measures.removeAt(position))
  26. notifyItemMoved(position, 0)
  27. }
  28. }
  29. }
  30.  
  31. override fun getItemCount(): Int {
  32. return item.measures.size
  33. }
  34. }
  35.  
  36. class DiffViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
  37.  
  38. val labelTv: TextView = itemView.findViewById(R.id.label_tv)
  39. val measureEdit: EditText = itemView.findViewById(R.id.measure_edit)
  40.  
  41. fun onBind(
  42. label: String,
  43. currentValue: Double,
  44. watcher: TextWatcher,
  45. listener: View.OnFocusChangeListener
  46. ) {
  47. labelTv.text = label
  48. measureEdit.setText(currentValue.toString())
  49. measureEdit.addTextChangedListener(watcher)
  50. measureEdit.onFocusChangeListener = listener
  51. }
  52.  
  53. }
  54.  
  55. class MyDiff : DiffUtil.ItemCallback<Pair<String, Double>>() {
  56. override fun areItemsTheSame(
  57. oldItem: Pair<String, Double>,
  58. newItem: Pair<String, Double>
  59. ): Boolean {
  60. return oldItem.first == newItem.first
  61. }
  62.  
  63. override fun areContentsTheSame(
  64. oldItem: Pair<String, Double>,
  65. newItem: Pair<String, Double>
  66. ): Boolean {
  67. return oldItem.first == newItem.first && oldItem.second == newItem.second
  68. }
  69. }
Add Comment
Please, Sign In to add comment