Меню не будет отображаться в Активности - PullRequest
0 голосов
/ 12 марта 2019

У меня есть меню, которое не будет отображаться в моей деятельности.У меня есть основное действие и отдельное действие, которое содержит список элементов, по которым пользователь должен выполнять поиск.Тем не менее, меню не отображается в активности для поиска, поэтому при вводе строки для поиска ничего не происходит.

Цель состояла в том, чтобы получить меню в операции поиска, чтобы позволить пользователюдля поиска элементов с использованием SearchView и RecyclerView

Я очень плохо знаком с Android Studio, поэтому любая помощь будет принята с благодарностью.

Вот меню для SearchView

<?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/action_search"
        android:icon="@drawable/ic_search"
        android:title="Search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />

    <item android:id="@+id/action_search2"
        android:icon="@drawable/ic_search"
        android:title="Search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />


</menu>

Вот макет xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">


    <include
        layout="@layout/activity_search_toolbar"/>



    <android.support.v7.widget.SearchView
        android:id="@+id/action_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:menu="@menu/search_menu">


    </android.support.v7.widget.SearchView>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme">

        <Button
            android:id="@+id/GoBackbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GO BACK" />

        <!--<android.support.v7.widget.SearchView-->
            <!--android:id="@+id/searchBar"-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content">-->
            <!--&lt;!&ndash;app:menu="@menu/search_menu"&ndash;&gt;-->


        <!--</android.support.v7.widget.SearchView>-->

    </android.support.v7.widget.Toolbar>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

и панель инструментов для добавления к макету

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:id="@+id/search_toolbar"
    android:background="?attr/colorPrimary">

</android.support.v7.widget.Toolbar>

Здесь я раздуваю search_menu

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) searchItem.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);

            return false;
        }
    });
    return true;
}

Наконец, это часть моего класса Adapter для фильтрации элементов в RecyclerView

 @Override
public Filter getFilter() {
    return locationFilter;
}

private Filter locationFilter = new Filter(){
    @Override
    protected FilterResults performFiltering(CharSequence constraint){
        List<Location> filteredLocationList = new ArrayList<>();

        if(constraint == null || constraint.length() == 0){
            filteredLocationList.addAll(locationListFull);
        } else{
            String filterPattern = constraint.toString().toLowerCase().trim();

            for(Location location : locationListFull){
                if(location.getTitle().toLowerCase().contains(filterPattern)){
                    filteredLocationList.add(location);
                }
                // Add another if statement here if we want to be able to search
                // descriptions as well
            }
        }
        FilterResults results = new FilterResults();
        results.values = filteredLocationList;
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results){
        locationList.clear();
        locationList.addAll((List)results.values);
        notifyDataSetChanged();
    }
};

Также, если есть другой способ использовать SearchView с RecyclerView, кроме создания меню для SearchView, это было бы очень полезно.Я пытался найти способы доступа к SearchView, кроме того, создав новое меню, но не нашел ничего полезного.

1 Ответ

0 голосов
/ 12 марта 2019

Подготовьте стандартное меню параметров экрана для отображения.Это вызывается прямо перед отображением меню, каждый раз, когда оно отображается.Вы можете использовать этот метод, чтобы эффективно включать / отключать элементы или иным образом динамически изменять содержимое.

https://developer.android.com/reference/android/app/Activity.html#onPrepareOptionsMenu(android.view.Menu)

Вам необходимо переопределить onPrepareOptionsMenu и настроить там свое поисковое представление вместоделать это в onCreateOptionsMenu

...