-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainActivity.kt
94 lines (70 loc) · 2.71 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package friendlyrobot.nyc.timetrials
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.squareup.moshi.Moshi
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.item_book.view.*
class MainActivity : AppCompatActivity() {
private lateinit var bookAdapter: BookAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this)
bookAdapter = BookAdapter()
recyclerView.adapter = bookAdapter
val moshi = Moshi.Builder().build()
val smallResponse = moshi.adapter<ApiBookResponse>(ApiBookResponse::class.java).fromJson(simpleSearchResponse)
for (i in 1..10) {
smallResponse?.docs?.forEach {
bookAdapter.add(it.toBook())
}
}
bookAdapter.notifyDataSetChanged()
searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
Log.e("MainActivity", "onQueryTextSubmit $query")
bookAdapter.clear()
indeterminateBar.visibility = View.VISIBLE
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
return false
}
})
}
}
class BookAdapter : RecyclerView.Adapter<BookAdapter.BookViewHolder>() {
private val books = mutableListOf<Book>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder {
val inflater = LayoutInflater.from(parent.context)
val holder = BookViewHolder(inflater.inflate(R.layout.item_book, parent, false))
return holder
}
override fun getItemCount() = books.size
override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
books.getOrNull(position)?.let { holder.bind(it) }
}
class BookViewHolder(bookView: View) : RecyclerView.ViewHolder(bookView) {
fun bind(book: Book) {
itemView.book_title.text = book.title
}
}
fun add(book: Book) {
books.add(book)
}
fun addAllAndClear(booksToAdd: List<Book>) {
books.clear()
books.addAll(booksToAdd)
notifyDataSetChanged()
}
fun clear() {
books.clear()
notifyDataSetChanged()
}
}