Add search icon on action bar android

前端 未结 2 1975
北荒
北荒 2021-01-30 18:32

Good days guys.

I have a search icon in action bar as image below

When it is clicked, I want the action bar change to editText and has a se

2条回答
  •  清酒与你
    2021-01-30 19:10

    You should use inbuilt android SearchView this hold good according Android UI Patterns

    menu.xml

    
        
    
    

    Activity code

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_transaction_search, menu);
            final MenuItem searchItem = menu.findItem(R.id.action_search);
    
            if (searchItem != null) {
                searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
                searchView.setOnCloseListener(new SearchView.OnCloseListener() {
                    @Override
                    public boolean onClose() {
                     //some operation
                    }
                });
                searchView.setOnSearchClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //some operation
                    }
                });
                EditText searchPlate = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
                searchPlate.setHint("Search");
                View searchPlateView = searchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
                searchPlateView.setBackgroundColor(ContextCompat.getColor(this, android.R.color.transparent));
                // use this method for search process
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        // use this method when query submitted
                        Toast.makeText(context, query, Toast.LENGTH_SHORT).show();
                        return false;
                    }
    
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        // use this method for auto complete search process
                        return false;
                    }
                });
                SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    
            }
            return super.onCreateOptionsMenu(menu);
        }
    
        @Override
        public void onBackPressed() {
            if (!searchView.isIconified()) {
                searchView.setIconified(true);
                findViewById(R.id.default_title).setVisibility(View.VISIBLE);
            } else {
                super.onBackPressed();
            }
        }
    

    make sure to inflate menu :D

提交回复
热议问题