set app icon to right side in activity tool bar

后端 未结 3 961
执笔经年
执笔经年 2020-12-30 12:33

I am working with the \'AppCompact\' library and faced some problems with layout/positioning. I want to position the App icon on the right hand side of the \'ActionBar\'. O

3条回答
  •  梦毁少年i
    2020-12-30 13:07

    There is no way android provides to set app icon at right side of actionbar but you can still do that.

    Create a menu, say main_menu.xml

    
    
    
          //set showAsAction always
                                        //and this should be the only menu item with show as action always
    
    
    

    Now just override onCreateOptionsMenu in your activity class.

    add this in MainActivity.java

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    

    It's done! Your app icon will be visible on right side of ActionBar now.

    If you have more than one item in menu then override onPrepareOptionsMenu in activity class and set setEnabled(false) for menu item having app icon, doing this prevents your icon to be clickable.

    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        menu.findItem(R.id.menu_item).setEnabled(false);
    
        return super.onPrepareOptionsMenu(menu);
    }
    

    Now your MainActivity.java file would look like

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    
        switch(item.getItemId()){
            case R.id.menu_item:   //this item has your app icon
                return true;
    
            case R.id.menu_item2:  //other menu items if you have any
                //add any action here
                return true;
    
            case ... //do for all other menu items
    
            default: return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        menu.findItem(R.id.menu_item).setEnabled(false);
    
        return super.onPrepareOptionsMenu(menu);
    }
    

    This is the only trick you can use to set app icon on right side.

提交回复
热议问题