English subtitles

← Initialize the Adapter - Developing Android Apps

Get Embed Code
10 Languages

Showing Revision 14 created 05/25/2016 by Udacity Robot.

  1. In our code, we're going to initialize
    the adapter
  2. within the Placeholder Fragment
    onCreate view method.
  3. Because that's where we want the ListView
    to be populated with data.
  4. We're using a ArrayAdapter, and we can
    initialize it with four parameters:
  5. A context,
  6. the ID of a list item layout,
  7. the ID of a text view within that list item layout,
  8. as well as a list of data.
  9. We'll go through each of these
    parameters one by one now.
  10. First, for context -- it contains global
    information about the app environment.
  11. It allows us to access system
    services and resources,
  12. as well as the application specific
    resources that we've defined.
  13. We use the fragments containing
    activity as the context.
  14. So, we're going to call getActivity
    for our parameter here.
  15. Since the adapter needs to know
    the layout for each list item,
  16. it needs some reference
    to the XML layouts that we've defined.
  17. The r.java class is a generated file
    that creates human readable identifiers
  18. for our resources.
  19. For the list item layout, we refer to it
    in code as R.layout.list_item_forecast.
  20. This was the name of the XML file
    that we created earlier.
  21. Next, the array adapter needs to know
    how to take the weather forecast string
  22. and set that to be displayed
    in a text view.
  23. So you pass in the ID of the text view
    that we defined earlier,
  24. in the list item layout.
  25. Even though these two
    resource IDs look similar,
  26. one starts with R.layout
    while the other starts with R.id.
  27. R.layout refers to a layout file, while
    an ID refers to a specific XML element
  28. with the matching ID attribute.
  29. And lastly, we pass in weekForecast,
  30. which is the array list of forecast data
    that we defined earlier.
  31. Now go ahead and initialize your adapter.
  32. Check this box when you're done.