这是什么意思:return @ OnNavigationItemSelectedListener

时间:2018-11-29 19:31:05

标签: android kotlin

以下代码中的“ return @ OnNavigationItemSelectedListener”是什么意思:

class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                message.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                message.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }
}

1 个答案:

答案 0 :(得分:1)

从Kotlin文档中:

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach lit@{
        if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
        print(it)
    }
    print(" done with explicit label")
}
  

return-expression从最近的封闭函数foo返回。 (请注意,只有传递给内联函数的lambda表达式才支持这种非本地返回。)如果需要从lambda表达式返回,则必须对其进行标记并限定返回值:

See more here