Set search hint dynamically

后端 未结 7 1446
悲哀的现实
悲哀的现实 2021-02-08 04:38

Does anybody knows how to set android search dialog hint dynamically? T have try to do something like:




        
7条回答
  •  抹茶落季
    2021-02-08 04:41

    There is a much simpler answer than any of the above. It loads the default searchable.xml for your activity, and then uses java reflection to update the private mHintId field inside the SearchableInfo instance:

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        SearchManager searchManager = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
        SearchableInfo si = searchManager.getSearchableInfo( getActivity().getComponentName() );
    
        try {
            Field mHintId = si.getClass().getDeclaredField("mHintId");
            mHintId.setAccessible(true);
            mHintId.setInt(si, R.string.your_custom_hint);
        } catch (Exception e) {
        }
    
        MenuItem mi = menu.findItem(R.id.menu_search);
        SearchView searchView = (SearchView)mi.getActionView();
        searchView.setSearchableInfo( si );
    }
    

提交回复
热议问题