• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.deskclock.actionbarmenu
18 
19 import android.app.Activity
20 import android.view.Menu
21 import android.view.MenuItem
22 
23 /**
24  * Activity scoped singleton that manages action bar menus. Each menu item is controlled by a
25  * [MenuItemController] instance.
26  */
27 class OptionsMenuManager {
28 
29     private val mControllers: MutableList<MenuItemController?> = ArrayList()
30 
31     /**
32      * Add one or more [MenuItemController] to the actionbar menu.
33      *
34      * This should be called in [Activity.onCreate].
35      */
addMenuItemControllernull36     fun addMenuItemController(vararg controllers: MenuItemController?): OptionsMenuManager {
37         mControllers.addAll(controllers)
38         return this
39     }
40 
41     /**
42      * Inflates [Menu] for the activity.
43      *
44      * This method should be called during [Activity.onCreateOptionsMenu].
45      */
onCreateOptionsMenunull46     fun onCreateOptionsMenu(menu: Menu) {
47         for (controller in mControllers) {
48             controller?.onCreateOptionsItem(menu)
49         }
50     }
51 
52     /**
53      * Prepares the popup to displays all required menu items.
54      *
55      * This method should be called during [Activity.onPrepareOptionsMenu] (Menu)}.
56      */
onPrepareOptionsMenunull57     fun onPrepareOptionsMenu(menu: Menu) {
58         for (controller in mControllers) {
59             controller?.let {
60                 val menuItem: MenuItem? = menu.findItem(controller.id)
61                 if (menuItem != null) {
62                     controller.onPrepareOptionsItem(menuItem)
63                 }
64             }
65         }
66     }
67 
68     /**
69      * Handles click action for a menu item.
70      *
71      * This method should be called during [Activity.onOptionsItemSelected].
72      */
onOptionsItemSelectednull73     fun onOptionsItemSelected(item: MenuItem): Boolean {
74         val itemId: Int = item.getItemId()
75         for (controller in mControllers) {
76             if (controller?.id == itemId && controller.onOptionsItemSelected(item)) {
77                 return true
78             }
79         }
80         return false
81     }
82 }