Menu.kt revision 9c80550cbbe357a89e2abeeb9c7769fcaefc3a65
1/* 2 * Copyright (C) 2018 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@file:Suppress("NOTHING_TO_INLINE") 18 19package androidx.core.view 20 21import android.view.Menu 22import android.view.MenuItem 23 24/** 25 * Returns the menu at [index]. 26 * 27 * @throws IndexOutOfBoundsException if index is less than 0 or greater than or equal to the count. 28 */ 29inline operator fun Menu.get(index: Int): MenuItem = getItem(index) 30 31/** Returns `true` if [item] is found in this menu. */ 32operator fun Menu.contains(item: MenuItem): Boolean { 33 @Suppress("LoopToCallChain") 34 for (index in 0 until size) { 35 if (getItem(index) == item) { 36 return true 37 } 38 } 39 return false 40} 41 42/** Returns the number of items in this menu. */ 43inline val Menu.size get() = size() 44 45/** Returns true if this menu contains no items. */ 46inline fun Menu.isEmpty() = size() == 0 47 48/** Returns true if this menu contains one or more items. */ 49inline fun Menu.isNotEmpty() = size() != 0 50 51/** Performs the given action on each item in this menu. */ 52inline fun Menu.forEach(action: (item: MenuItem) -> Unit) { 53 for (index in 0 until size()) { 54 action(getItem(index)) 55 } 56} 57 58/** Performs the given action on each item in this menu, providing its sequential index. */ 59inline fun Menu.forEachIndexed(action: (index: Int, item: MenuItem) -> Unit) { 60 for (index in 0 until size()) { 61 action(index, getItem(index)) 62 } 63} 64 65/** Returns a [MutableIterator] over the items in this menu. */ 66operator fun Menu.iterator() = object : MutableIterator<MenuItem> { 67 private var index = 0 68 override fun hasNext() = index < size() 69 override fun next() = getItem(index++) ?: throw IndexOutOfBoundsException() 70 override fun remove() = removeItem(--index) 71} 72