我正在制作一个只是练习用的计算器,但我发现按钮太多了。我将他们的 id 命名为 button+row+col ex) row=5, col=4 -> id=button54
由于我必须攻击每个按钮的侦听器,因此我发现手动执行此操作非常烦人。喜欢,
findViewById(R.id.button11).setOnClickListener(this);
findViewById(R.id.button12).setOnClickListener(this);
...
findViewById(R.id.button95).setOnClickListener(this);
我可以这样做吗
for(int i=1; i<=9; i++){
for(int j=1; j<=5; j++){
findViewById(R.id."button"+Integer.toString(i) + Integer.toString(j)).setOnClickListener(this);
}
}
或其他方式使这更容易。
由于您正在使用很多按钮,我建议您将它们全部放入一个 ViewGroup(如 LinearLayout、FrameLayout 或类似的东西)中,然后遍历该 ViewGroup 的每个 View,检查其实例,然后分配点击侦听器。
这是一些伪代码,因为我忘记了 Java 是如何工作的
ViewGroup viewGroup = findViewById(R.id.yourViewGroupName);
for each child in viewGroup.getChildren {
if child is of type Button {
child.setOnClickListener(this);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句