如何在Java中访问相似名称的变量

huangapple go评论76阅读模式
英文:

how accessing similar name variables in java

问题

Sure, here's the translation of the provided content:

我有5个按钮,分别命名为btn1、btn2、btn3、btn4、btn5,还有一个整数变量numberInt。

我希望当numberInt的值变成一个数字时,对应编号的按钮变为不可见状态。

像这样:

if (numberInt == 1){
   btn1.setVisibility(View.GONE);
}else if (numberInt == 2){
   btn2.setVisibility(View.GONE);

是否有办法在 'btn' 关键字之后使用numberInt?因为当按钮数量较多时编写这么多的if语句很麻烦。

抱歉表达不清楚。

英文:

i have 5 button as btn1, btn2, btn3, btn4, btn5 and a integer variable as numberInt

i want when numberInt changed to a number, button with that number becomes invisible
like this:

if (number == 1){
   btn1.setVisibility(View.GONE);
}else if (number == 2){
   btn2.setVisibility(View.GONE);

is there any way to use numberInt end of 'btn' keyword? because is hard to write if loops when buttons is too many.

Sorry for bad explaining.

答案1

得分: 4

把所有的按钮放入一个列表中

List<Button> buttons = new ArrayList();
buttons.add(btn1);
buttons.add(btn2);

然后通过索引引用它们

buttons.get(number);

在运行时无法构建标识符,例如:

btn${number}.setVisibility(View.GONE); // 不是有效的 Java 语法

在一些脚本语言中可以做到这种操作,但在 Java 中不行。

英文:

Put all the buttons in a list

List&lt;Button&gt; buttons = new ArrayList();
buttons.add(btn1);
buttons.add(btn2);

then refer to them by index

buttons.get(number);

There is no way to construct an identifier at runtime e.g.

btn${number}.setVisibility(View.GONE); // not valid java

You can do that kind of thing in some scripting languages, but not in Java.

答案2

得分: 0

你的按钮都放在一个数组中,就不需要使用“If循环”。因为数组的索引是“int”类型,可以用于你的优势。

Button[] buttons = {btn0, btn1, btn2, ...};

使用以下方法来更新视图的可见性

public void setInvisibleButton(int i){
   buttons[i].setVisibility(View.GONE)
}
英文:

You need not use 'If loop' if all your buttons are put in an array. Since arrays have 'int' as index that can be used to your advantage.

Button[] buttons = {btn0, btn1, btn2, ...};

use a method as below to update view's visibility

public void setInvisibleButton(int i){
   buttons[i].setVisibility(View.GONE)
}

huangapple
  • 本文由 发表于 2020年8月25日 00:00:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63564587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定