How to change the position of menu items on actionbar

后端 未结 4 1141
无人共我
无人共我 2021-02-07 14:51

I\'m developing one application in which I have to add a custom layout on actionbar. Adding the custom layout is done, but when I\'m adding the menu items on actionbar my custom

4条回答
  •  一个人的身影
    2021-02-07 15:06

    I assume you are setting your custom view as a custom view in the action bar. If you are using ActionbarSherlock you can instead add the custom view as a normal menu item and set an action view for it using .setActionView(yourCustomView or yourCustomLayoutId). You can then set .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) to display the view. Just make sure your custom view is set to width wrap_content or otherwise it will push the other menu items off the screen. This might also work without ActionbarSherlock, but I haven't tried it there yet.

    EDIT: Try modifying your onCreateOptionsMenu method

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.websearch_menu, menu);
    
        // add this
        menu.add(Menu.NONE, 0, Menu.NONE, "custom")
            .setActionView(R.layout.header)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    
        return true;
    }
    

    and remove this from your onCreate method

    actionBar.setDisplayShowCustomEnabled(true);
    cView = getLayoutInflater().inflate(R.layout.header, null);
    actionBar.setCustomView(cView);
    

    EDIT:

    If you need to reference the views from your custom layout, you can do this in your onCreateOptionsMenu method as follows (note: I wrote this code in the browser, so no guarantee that I didn't make a typo or something):

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        // inflate the menu and add the item with id viewId,
        // which has your layout as actionview
    
        View actionView = menu.getItem(viewId).getActionView();
        View viewFromMyLayout = actionView.findViewById(R.id.viewFromMyLayout);
    
        // here you can set listeners to your view or store a reference 
        // to it somewhere, so you can use it later
    
        return true;
    }
    

提交回复
热议问题