Здравствуйте!
Пытаюсь, при нажатии на кнопку сделать повторную загрузку списка, однако метод clear у адаптера не найден, подскажите как очистить список в адаптере?
class TodoAdapter : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {
inner class TodoViewHolder(val binding: ItemTodoBinding) : RecyclerView.ViewHolder(binding.root)
private val diffCallback = object : DiffUtil.ItemCallback<Todo>() {
override fun areItemsTheSame(oldItem: Todo, newItem: Todo): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Todo, newItem: Todo): Boolean {
return oldItem == newItem
}
}
private val differ = AsyncListDiffer(this, diffCallback)
var todos: List<Todo>
get() = differ.currentList
set(value) { differ.submitList(value) }
override fun getItemCount() = todos.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
return TodoViewHolder(ItemTodoBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
))
}
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
holder.binding.apply {
val todo = todos[position]
tvTitle.text = todo.title
cbDone.isChecked = todo.completed
}
}
}
const val TAG = "MainActivity"
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var binding: ActivityMainBinding
private lateinit var todoAdapter: TodoAdapter
private lateinit var button: Button
private val job = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + job)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
button = findViewById(R.id.button)
button.setOnClickListener(this)
setupRecyclerView()
lifecycleScope.launchWhenCreated {
binding.progressBar.isVisible = true
loadTodos()
binding.progressBar.isVisible = false
}
}
private suspend fun loadTodos(){
val response = try {
RetrofitInstance.api.getTodos()
// Toast.makeText(this@MainActivity,t.isSuccessful.toString(),Toast.LENGTH_LONG)
} catch(e: IOException) {
Log.e(TAG, "IOException, you might not have internet connection")
binding.progressBar.isVisible = false
return
} catch (e: HttpException) {
Log.e(TAG, "HttpException, unexpected response")
binding.progressBar.isVisible = false
return
}
if(response.isSuccessful && response.body() != null) {
todoAdapter.todos = response.body()!!
} else {
Log.e(TAG, "Response not successful")
}
}
private fun setupRecyclerView() = binding.rvTodos.apply {
todoAdapter = TodoAdapter()
adapter = todoAdapter
layoutManager = LinearLayoutManager(this@MainActivity)
}
override fun onClick(p0: View?) {
lifecycleScope.launch {
Toast.makeText(this@MainActivity,"dfdfdf",Toast.LENGTH_LONG).show()
binding.progressBar.isVisible = true
//МЕТОД НЕ НАЙДЕН
todoAdapter.clear()
loadTodos()
binding.progressBar.isVisible = false
}
}
override fun onDestroy(){
job.cancel()
super.onDestroy()
}
}