17
17
package com.example.android.marsphotos.overview
18
18
19
19
import android.os.Bundle
20
- import android.view.LayoutInflater
21
- import android.view.View
22
- import android.view.ViewGroup
20
+ import android.view.*
23
21
import androidx.fragment.app.Fragment
24
- import androidx.fragment.app.viewModels
22
+ import androidx.lifecycle.ViewModelProvider
23
+ import com.example.android.marsphotos.R
25
24
import com.example.android.marsphotos.databinding.FragmentOverviewBinding
26
- import com.example.android.marsphotos.databinding.GridViewItemBinding
25
+ import com.example.android.marsphotos.network.MarsApiFilter
27
26
28
27
/* *
29
28
* This fragment shows the the status of the Mars photos web services transaction.
30
29
*/
31
30
class OverviewFragment : Fragment () {
32
31
33
- private val viewModel: OverviewViewModel by viewModels()
32
+ private val viewModel: OverviewViewModel by lazy {
33
+ ViewModelProvider (this ).get(OverviewViewModel ::class .java)
34
+ }
34
35
35
36
/* *
36
37
* Inflates the layout with Data Binding, sets its lifecycle owner to the OverviewFragment
37
38
* to enable Data Binding to observe LiveData, and sets up the RecyclerView with an adapter.
38
39
*/
39
- override fun onCreateView (
40
- inflater : LayoutInflater , container : ViewGroup ? ,
41
- savedInstanceState : Bundle ?
42
- ): View ? {
40
+ override fun onCreateView (inflater : LayoutInflater , container : ViewGroup ? ,
41
+ savedInstanceState : Bundle ? ): View ? {
43
42
val binding = FragmentOverviewBinding .inflate(inflater)
44
43
// val binding = GridViewItemBinding.inflate(inflater)
45
44
@@ -49,11 +48,29 @@ class OverviewFragment : Fragment() {
49
48
// Giving the binding access to the OverviewViewModel
50
49
binding.viewModel = viewModel
51
50
52
- // Display a grid of images
51
+ // Sets the adapter of the photosGrid RecyclerView
53
52
binding.photosGrid.adapter = PhotoGridAdapter ()
54
53
55
54
setHasOptionsMenu(true )
56
-
57
55
return binding.root
58
56
}
57
+
58
+ /* *
59
+ * Inflates the overflow menu that contains filtering options.
60
+ */
61
+ override fun onCreateOptionsMenu (menu : Menu , inflater : MenuInflater ) {
62
+ inflater.inflate(R .menu.overflow_menu, menu)
63
+ super .onCreateOptionsMenu(menu, inflater)
64
+ }
65
+
66
+ override fun onOptionsItemSelected (item : MenuItem ): Boolean {
67
+ viewModel.updateFilter(
68
+ when (item.itemId) {
69
+ R .id.show_rent_menu -> MarsApiFilter .SHOW_RENT
70
+ R .id.show_buy_menu -> MarsApiFilter .SHOW_BUY
71
+ else -> MarsApiFilter .SHOW_ALL
72
+ }
73
+ )
74
+ return true
75
+ }
59
76
}
0 commit comments