带有Activity和TabFragments的ToolBar SearchView

时间:2016-02-16 05:44:02

标签: android android-fragments android-activity searchview android-collapsingtoolbarlayout

我需要在ToolBar中实现SearchView。我试着这样做。在MainActivity中它显示了Log.e中的搜索文本。但我需要将这个搜索查询发送到活动的片段。我正在使用3个标签片段。 从我需要将搜索查询传递到Fragment

这是我的代码..

MainActivity:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(false);
//        searchView.getOutlineProvider();
        searchView.setOnQueryTextListener(this);
        searchView.setOnCloseListener(this);

        return super.onCreateOptionsMenu(menu);
    } 

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                break;
            case R.id.action_addCart:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

@Override
    public boolean onClose() {
        passQuery = "";
        System.out.println("Restaurant close");
        return true;
    }

@Override
public boolean onQueryTextSubmit(String query) {

    passQuery = query;
    System.out.println("Restaurant onQueryTextSubmit =" + query);
    return true;
}


@Override
public boolean onSearchRequested() {
    Bundle appData = new Bundle();
    appData.putBoolean(SEARCHING_DATA, true);
    startSearch(null, false, appData, true);
    System.out.println("Restaurant onSearchRequested = " + appData);
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {
    passQuery = newText;
    System.out.println("Restaurant onQueryTextSubmit =" + newText);
    return true;
}

ViewPageradapter:

 ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
         adapter.addFrag(new TabFragment_1(), "WHAT'S HOT!"); 
         adapter.addFrag(new TabFragment_2(), "PIZZAS");  
         adapter.addFrag(new TabFragment_3(), "ICE CREAMS");  

                    viewPager.setAdapter(adapter);

                    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
                    tabLayout.setupWithViewPager(viewPager);

请帮我通过android中的viewPager传递搜索查询

1 个答案:

答案 0 :(得分:0)

在片段中创建一个方法,并将适配器编码放在该方法中。 然后从OnQueryTextChange或OnQueryTextSubmit调用该方法。 以下是在片段中调用方法的代码

YourFragment fragment = (YourFragment)getFragmentManager().
                        findFragmentById(R.id.fragment_container);
                        fragment.yourMethod(passQuery);