Android SearchView does not work

前端 未结 8 1792
心在旅途
心在旅途 2021-01-11 17:25

I tried to update all the libraries, but i still got errors. I am able to run the app on the simulator, but when I export the APK and run it on a real android device, the ap

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-11 17:58

    For API before 11 you should initialize Action Bar Items in compatibility mode:

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            MenuItem searchMenuItem = menu.findItem(R.id.action_search);
            SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchMenuItem);
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            return true;
        }
    

    Update:
    So, I tried to reproduce it in API 8 emulator and on 4.4 KitKat. Unfortunately, my 2.3.8 device got bricked a while ago, so could not check in hardware with low API. What I can suggest you:
    1. Check that SearchView is imported from android.support.v7.widget.SearchView;
    2. Check menu resource is correct:

    
    
          <----------- use compatible namespace
    
        
    
    
    

    3. return true from onCreateOptionsMenu if there's no underlying processing (Activity class is not subclassed)

    UPDATE2: GOT IT! You probably extends from Activity class. Should be ActioBarActivity:

    public class MainActivity extends ActionBarActivity {
    ...
    

提交回复
热议问题