Menu.kt revision 88f4feab5dc6fdc0e547bbad233126f64e0c843d
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/** Removes [item] from this menu. */ 43inline operator fun Menu.minusAssign(item: MenuItem) = removeItem(item.itemId) 44 45/** Returns the number of items in this menu. */ 46inline val Menu.size get() = size() 47 48/** Returns true if this menu contains no items. */ 49inline fun Menu.isEmpty() = size() == 0 50 51/** Returns true if this menu contains one or more items. */ 52inline fun Menu.isNotEmpty() = size() != 0 53 54/** Performs the given action on each item in this menu. */ 55inline fun Menu.forEach(action: (item: MenuItem) -> Unit) { 56 for (index in 0 until size()) { 57 action(getItem(index)) 58 } 59} 60 61/** Performs the given action on each item in this menu, providing its sequential index. */ 62inline fun Menu.forEachIndexed(action: (index: Int, item: MenuItem) -> Unit) { 63 for (index in 0 until size()) { 64 action(index, getItem(index)) 65 } 66} 67 68/** Returns a [MutableIterator] over the items in this menu. */ 69operator fun Menu.iterator() = object : MutableIterator<MenuItem> { 70 private var index = 0 71 override fun hasNext() = index < size() 72 override fun next() = getItem(index++) ?: throw IndexOutOfBoundsException() 73 override fun remove() = removeItem(--index) 74} 75 76/** Returns a [Sequence] over the items in this menu. */ 77val Menu.children: Sequence<MenuItem> 78 get() = object : Sequence<MenuItem> { 79 override fun iterator() = this@children.iterator() 80 } 81