Remove icon/title for actionbar with expanded SearchView?

后端 未结 3 1136
孤城傲影
孤城傲影 2021-01-11 22:41

I created a new project, targeting api 11 and above. I have an activity where I want a SearchView expanded by default:

@Override
public void onCreateOptionsM         


        
3条回答
  •  遥遥无期
    2021-01-11 22:45

    Even though the icon is transparent, it still takes up the space:

    getActionBar().setIcon(android.R.color.transparent);
    

    Remove this line and add:

    getActionBar().setDisplayShowHomeEnabled(false);
    

    Now, you should have the SearchView take up all the available space.

    Action items that can be collapsed have a max width. The only workaround I can think of is the following:

    public class GreatAndroid extends FragmentActivity {
        private SearchView mSearchView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            getActionBar().setDisplayShowHomeEnabled(false);
            getActionBar().setDisplayShowTitleEnabled(false);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
    
            getMenuInflater().inflate(R.menu.menu_search, menu);
            MenuItem mi = menu.findItem(R.id.action_search);
            mSearchView = (SearchView) mi.getActionView();
            mSearchView.setIconifiedByDefault(false);
    
            // You can use Display.getSize(Point) from API 13 onwards.
            // For API 11 and 12, use Display.getWidth()
    
            final Point p = new Point();
    
            getWindowManager().getDefaultDisplay().getSize(p);
    
            // Create LayoutParams with width set to screen's width
            LayoutParams params = new LayoutParams(p.x, LayoutParams.MATCH_PARENT);
    
            mSearchView.setLayoutParams(params);
    
            return true;
        }
    }
    

    Although it looks like there's still space to the left, you can use mSearchView.setBackgroundColor(Color.RED); to see that there really isn't.

提交回复
热议问题