我是 Android 新手。我只懂C和C++。我在 github 上看到了以下 for
循环引用。
for (int clickableId : clickableIds) {
view.findViewById(clickableId).setOnClickListener(this);
}
我在 google 上搜索了有关 android 的基于范围的 for 循环,因为我了解 C++,并且在 C++ 中语法是基于范围的 for 循环。但是,我找不到任何引用。
所以,
这个 for 循环有什么作用?
我应该何时何地使用它?
最佳答案
这是github中的完整代码:
final int[] clickableIds = new int[]{
R.id.easy_mode_button,
R.id.hard_mode_button,
R.id.show_achievements_button,
R.id.show_leaderboards_button,
R.id.sign_in_button,
R.id.sign_out_button
};
for (int clickableId : clickableIds) {
view.findViewById(clickableId).setOnClickListener(this);
}
这意味着 int clickableId
正在遍历数组 clickableIds
。因此它进入了第一个R.id.easy_mode_button
,然后在for循环内onclicklistener
方法将被调用。
这个 for 循环称为增强型 for 循环,这是它的语法:
for (int myValue : myArray) {
onClickListener(this) //this means current class is implementing onClickListener.
因此,进入 for 循环后,会调用 onClickListener(this)
,当单击按钮时,会调用 onClick()
。
关于java - "for (int clickableId : clickableIds)"有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220310/