Используйте виджет SearchView в ActionBar и фрагмент - PullRequest
1 голос
/ 03 апреля 2020

Я пытаюсь использовать виджет SearchView для фильтрации данных из RecyclerView. В деятельности это работает как шарм. Однако во фрагменте обратные вызовы не запускаются.

Вот мой фрагмент:

class CowListFragment : Fragment(), SearchView.OnQueryTextListener {

    private val adapter = CowAdapter()

    private val args: CowListFragmentArgs by navArgs()

    private val viewModel: CowListViewModel by viewModels {
        InjectorUtils.provideCowViewModelFactory(this, args.livestockId)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentCowListBinding.inflate(inflater, container, false)
        context ?: return binding.root

        binding.cowRecyclerView.adapter = adapter
        subscribeUi(adapter)
        setHasOptionsMenu(true)

        return binding.root
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_cow_list, menu)
        val searchItem = menu.findItem(R.id.search_cow)
        val searchView = searchItem.actionView as SearchView
        searchView.setOnQueryTextListener(this)
    }

    private fun subscribeUi(adapter: CowAdapter) {
        viewModel.cows.observe(viewLifecycleOwner) { cows ->
            adapter.submitList(cows)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.search_cow -> {
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onQueryTextSubmit(query: String?): Boolean {
        query?.let { viewModel.filter(it) }
        return true
    }

    override fun onQueryTextChange(query: String?): Boolean {
        query?.let { viewModel.filter(it) }
        return true
    }
}

Вот мой макет фрагмента:

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

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/Theme.Bcs.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@android:color/transparent"
                app:contentInsetStartWithNavigation="0dp"
                app:layout_collapseMode="pin"
                app:menu="@menu/menu_cow_list"
                app:navigationIcon="@drawable/ic_detail_back"
                app:titleTextColor="?attr/colorOnSurface" />

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/cow_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:paddingStart="@dimen/card_side_margin"
            android:paddingTop="@dimen/header_margin"
            android:paddingEnd="@dimen/card_side_margin"
            app:layoutManager="androidx.recyclerview.widget.StaggeredGridLayoutManager"
            app:spanCount="@integer/grid_columns"
            tools:context=".MainActivity"
            tools:listitem="@layout/list_item_cow" />
    </androidx.appcompat.widget.LinearLayoutCompat>
</layout>

И меню :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/search_cow"
        android:icon="@drawable/ic_search"
        android:title="@string/search_title"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />

</menu>

Интересная вещь: если я остановлю конструктор в классе SearchView, я увижу, что создано несколько экземпляров. Похоже, что SearchView, к которому я добавляю слушателей, неправильный.

Полный код проекта вы можете получить здесь: Ссылка на Github https://github.com/Christian-Adventiel/body-condition-score-mobile

Любая помощь будет очень признательна. Спасибо!

1 Ответ

0 голосов
/ 05 апреля 2020

Добавление этого в функцию onCreateView решило проблему:

(activity as AppCompatActivity).setSupportActionBar(binding.toolbar)
...