Search code examples
androidandroid-studioonclicklistenerandroid-toolbarmenuitem

How use setOnClickListner on "custom" toolbar's menu items?


I want to set OnClick behaviour on menu items of custom toolbar in an activity. I found many answers of same thing but on the actionbar which comes from theme, no answer was found for clicking items of menu of custom material toolbar.

Note: I don't want to add Image button on toolbar.

Any help will be appreciated.


Solution

  • It is the same as with standard ActionBar.

    1) Replace ActionBar with your own material toolbar like so:

        @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                ...
                Toolbar toolbar = findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
                ...
    

    2) Override OnCreateOptions menu as usual:

    @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu_layout,menu);
            super.onCreateOptionsMenu(menu, inflater);
        }
    

    3) Handle clicks:

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.register: {
                    ...
                    return true;
                }
                default:
                    return super.onOptionsItemSelected(item);
            }
    
        }