[英]How do I efficiently change a property to multiple views/buttons in Android Studio?
I am getting started on Android Development and I've had trouble finding answers since I may not know how to word things properly. 我正在开始使用Android开发,但是我可能找不到正确的措辞,因此在寻找答案时遇到了麻烦。 What I am trying to do is setting all buttons invisible once I click on any button.
我想做的是一旦单击任何按钮,就将所有按钮设置为不可见。 The easy way out of it is this:
简单的方法是这样的:
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
Button button4 = findViewById(R.id.button4);
setInvisible(button1);
setInvisible(button2);
setInvisible(button3);
setInvisible(button4);
However I feel like this goes agains the DRY principle of programming. 但是我觉得这又像DRY编程原理一样。 I mean what if there were 100 buttons?
我的意思是如果有100个按钮怎么办?
After doing some thinking, I imagine I can use a loop and have i be the place holder for the numbers of each button. 经过一番思考,我想我可以使用一个循环,让我成为每个按钮的编号的占位符。 That way it would loop through every single one.
这样,它将遍历每一个。 However I am not sure on what methods to use.
但是我不确定使用哪种方法。
Thank you, 谢谢,
You can do it as follows: 您可以按照以下步骤进行操作:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int[] btnIds = new int[]{R.id.button1, R.id.button2, R.id.button3, R.id.button4};
private List<Button> buttonList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_group);
for(int i = 0; i < btn.length; i++){
buttonList.add(findViewById(btnIds[i]));
buttonList.get(i).setOnClickListener(this);
}
...
}
...
@Override
public void onClick(View v) {
//Either check for button ids or simply:
for (Button button : buttonList) {
button.setVisibility(View.INVISIBLE);//or View.GONE
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.