Connecting the adapter to the activity

Now we have an adapter that can map a List<Article> into views. We just need to use this adapter in conjunction with the RecyclerView that we added to the main activity.

For this, we will need some variables in our MainActivity class:

class MainActivity : AppCompatActivity() {

...
private lateinit var articles: RecyclerView
private lateinit var viewAdapter: ArticleAdapter
private lateinit var viewManager: RecyclerView.LayoutManager
...
}

We will instantiate all of them inside the onCreate() function:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

viewManager = LinearLayoutManager(this)
viewAdapter = ArticleAdapter()
articles = findViewById<RecyclerView>(R.id.articles).apply {
layoutManager = viewManager

adapter = viewAdapter
}

asyncLoadNews()
}

To be able to actually display the articles in the UI, we now need to update asyncLoadNews() so that it adds the elements retrieved to the adapter. We will replace the TODO that we left there previously:

launch(UI) {
// TODO: Refresh UI here
}

We now want to add code to hide the ProgressBar, and then add the new articles to viewAdapter:

launch(UI) {
findViewById<ProgressBar>(R.id.progressBar).visibility = View.GONE
viewAdapter.add(articles)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.96