如何在搜索小部件ActionBar中设置SearchView文本值?

时间:2014-12-17 17:06:33

标签: android

我的actionBar菜单包含两个acton:标准action_search和action_scan条形码。用zxing扫描条形码后,我想用onActivityResult中的条形码扫描内容值调用searchView,这可能吗?或者还有另一种方法可以做到这一点?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.artikel_liste, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            adapter.getFilter().filter(query);
            Log.d("Filter","on query submit: "+query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            adapter.getFilter().filter(newText);            
            Log.d("Filter","on change text: "+newText);

            return true;
        }
    };

    searchView.setOnQueryTextListener(textChangeListener);
    return super.onCreateOptionsMenu(menu);
}


public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    //retrieve scan result
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanningResult != null) {
        //we have a result
        String scanContent = scanningResult.getContents();
        String scanFormat = scanningResult.getFormatName();


        // how to call a searchView ??

        //SearchView(searchView).setQuery(scanContent, true);  
        //search.setIconifiedByDefault(false);
        //searchView.setQuery("test", false);

        //test
        //Toast toast = Toast.makeText(getApplicationContext(), "FORMAT: "+scanFormat+" ,CONTENT: "+scanContent, Toast.LENGTH_LONG);
        //toast.show();

    }else{
        Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT);
        toast.show();
    }
}

1 个答案:

答案 0 :(得分:1)

你应该考虑两件事:

1)onCreateOptionsMenu只会在首次创建时被调用。重新加载后,您将需要使用onPrepareOptionsMenu。

2)您可以使用以下方法告诉ActionBar刷新:

invalidateOptionsMenu();

因此在你的onActivityResult中你可以设置一个布尔值,然后调用invalidateOptionsMenu(),onPrepareOptionsMenu会被命中,你可以根据需要使用searchView。

希望它有所帮助。

祝你好运