Android androidx.SearchView 无效

Android androidx.SearchView is not working

我在我的项目中实现了 MaterialToolBar 中的 SearchView。除了最后一步,一切正常。当我在搜索栏中键入任何内容并单击键盘查找按钮时,它没有显示任何内容。请帮忙。

我的问题视频 https://drive.google.com/file/d/1GpE16D3drLGYp0ZetHgNlT8s7qZSFuWk/view?usp=drivesdk

Menu.xml

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

activity.xml

<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/category1_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingEnd="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:background="@color/dark_blue"
    app:menu="@menu/cart_share"
    tools:ignore="RtlSymmetry">

    <ImageView
        android:id="@+id/img_back_all_category"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:contentDescription="TODO"
        android:src="@drawable/ic_keyboard_arrow_left" />

    <TextView
        android:id="@+id/tv_all_categories"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="@string/product_name"
        android:fontFamily="@font/montserrat"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@color/white"
        android:layout_marginStart="25sp"/>
</com.google.android.material.appbar.MaterialToolbar>

java代码

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.cart_search_menu, menu);
    MenuItem menuItem = menu.findItem(R.id.menu_search);
    SearchView searchView = (SearchView) menuItem.getActionView();
    searchView.setQueryHint("Type here to search");
    searchView.setMaxWidth(android.R.attr.width);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            //getSearchResults(query); Also tried
            getSearchResults(searchView.getQuery().toString());
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            menuItem.collapseActionView();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cart_search_menu, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);
        
        SearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                
                // your code
                
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                // your code
                return false;
            }
        });
        return true;
    }

Check this screenshot试试这个

在菜单文件中:

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

在 kotlin 文件中:

  private var searchItem : MenuItem? = null
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.search_tenant_menu, menu)
    searchItem = menu.findItem(R.id.actionTenantSearch)

    val searchView = searchItem?.actionView as SearchView
    searchView.setOnQueryTextListener(object :
        SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(s: String): Boolean {
            CommonUtils.showToast(requireContext(), s)
            searchView.clearFocus()
            return true
        }

        override fun onQueryTextChange(s: String): Boolean {

            return true
        }
    })
    super.onCreateOptionsMenu(menu, inflater)
}

@vaibhav 是否为列表视图或回收视图实现了可过滤 class。之后在您的搜索查询中调用该可过滤方法。你会得到合适的结果 像这样

public class Adaptername extends RecyclerView.Adapter implements Filterable {

}

CustomFilter 过滤器;

@Override
public Filter getFilter() {
    if (filter == null) {
        filter = new CustomFilter();
    }
    return filter;
}

class CustomFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // TODO Auto-generated method stub
        FilterResults results = new FilterResults();
        if (constraint != null && constraint.length() > 0) {
            //CONSTARINT TO UPPER
            constraint = constraint.toString().toUpperCase();
            ArrayList<AllInOnetItem> filters = new ArrayList<AllInOnetItem>();
            //get specific items
            for (int i = 0; i < filterList.size(); i++) {
                if (filterList.get(i).getName().toUpperCase().contains(constraint)) {
                    AllInOnetItem p = new AllInOnetItem(filterList.get(i).getName(), filterList.get(i).getNumber(),filterList.get(i).getEmail());
                    filters.add(p);
                }
            }
            results.count = filters.size();
            results.values = filters;
        } else {
            results.count = filterList.size();
            results.values = filterList;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        // TODO Auto-generated method stub
        allInOnetItems = (ArrayList<AllInOnetItem>) results.values;
        notifyDataSetChanged();
    }
}

之后我更改了代码行的顺序,它工作正常。

之前:

super.onCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.category1_toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_product_list);

之后:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_list);
Toolbar toolbar = findViewById(R.id.category1_toolbar);
setSupportActionBar(toolbar);
<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    style="@style/Widget.MaterialComponents.AppBarLayout.PrimarySurface"
    android:fitsSystemWindows="true">


    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/topAppBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:title="@string/app_name"
        style="@style/Widget.MaterialComponents.Toolbar.PrimarySurface"
        android:elevation="0dp"
        app:navigationIcon="@drawable/ic_baseline_menu_24"
        app:menu="@menu/menu2"
       >
        <androidx.appcompat.widget.SearchView
            android:id="@+id/mySearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:clipToOutline="false"
            app:queryHint="Search"/>
    </com.google.android.material.appbar.MaterialToolbar>

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

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        app:layout_anchor="@+id/container"
        app:layout_anchorGravity="center" />

///主活动

binding.mySearch.setOnQueryTextListener(对象:SearchView.OnQueryTextListener{ 重写乐趣 onQueryTextSubmit(query: String?): Boolean { return 错误 }

            override fun onQueryTextChange(newText: String?): Boolean {
                Toast.makeText(this@MainActivity, newText, Toast.LENGTH_SHORT).show()
                return false
            }
        })