Chapter 27 Challenge Solution

First of all, I added searchView.onActionViewCollapsed() invoking. The example of solution you can find here: First part of challenge

Secondly, I have edited the layout .xml file a little

fragment_photo_gallery

`<?xml version="1.0" encoding="utf-8"?>

<
FrameLayout
xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:tools=“http://schemas.android.com/tools
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".PhotoGalleryActivity"
>

<android.support.v7.widget.RecyclerView
xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:tools=“http://schemas.android.com/tools
android:id="@+id/photo_recycler_view"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“com.bignerdranch.android.photogallery.PhotoGalleryActivity”/>


</
FrameLayout>
`

Then I have changed onCreateView, onCreateOptionsMenu and onPostExecute methods in order to work out the ProgressBar task.

onCreateView

`override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val v = inflater.inflate(R.layout.fragment_photo_gallery, container, false)

mProgressBar = v.findViewById(R.id.main_progress)
showProgressBar()

mPhotoRecyclerView = v.findViewById(R.id.photo_recycler_view)
mPhotoRecyclerView.layoutManager = GridLayoutManager(activity!!, 3)

updateItems()

setupAdapter()

return v

}`

onCreateOptionsMenu

`override fun onCreateOptionsMenu(
menu: Menu?,
menuInflater: MenuInflater?
) {
super.onCreateOptionsMenu(menu, menuInflater)
menuInflater!!.inflate(R.menu.fragment_photo_gallery, menu)
val searchItem = menu!!.findItem(R.id.menu_item_search)
val searchView = searchItem.actionView as SearchView

searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
  override fun onQueryTextSubmit(s: String): Boolean {
    Log.d(TAG, "QueryTextSubmit: $s")
    QueryPreferences.setStoredQuery(activity!!, query = s)
    searchView.onActionViewCollapsed()
    mItems = ArrayList()
    setupAdapter()
    showProgressBar()
    updateItems()
    return true
  }


}`

onPostExecute

private inner class FetchItemsTask(private val mQuery: String?) : AsyncTask<Void, Void, List<GalleryItem>>() { ... override fun onPostExecute(items: List<GalleryItem>) { hideProgressBar() mItems = items setupAdapter() } }

Util methods

`private fun showProgressBar() {
mProgressBar.visibility = View.VISIBLE
}

private fun hideProgressBar() {
mProgressBar.visibility = View.GONE
}`

In order to show screen without any pictures after search request and after clearing the SearchView, I refresh mItems by creating a new ArrayList. Can handle this without, what do you think?

Sorry for Kotlin and text formatting.