android:如何优雅地设置多个按钮 ID [英] android: how to elegantly set many button IDs

查看:17
本文介绍了android:如何优雅地设置多个按钮 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的活动中有很多按钮(一次只能看到其中的一个子集).我目前有这样的丑陋:

I have many buttons in my activity (only a subset of which are visible at a time). I currently have something ugly like this:

buttonID[0] = R.id.buttonr1b1;
buttonID[1] = R.id.buttonr1b2;
buttonID[2] = R.id.buttonr1b3;
buttonID[3] = R.id.buttonr1b4;
...
buttonID[35] = R.id.buttonr1b36;

for (int i = 0; i < 36; i++) {
    button[i] = (Button) findViewById(buttonID[i]);
}

有没有更优雅的方式来引用所有 R.id.buttonXXX ?它看起来非常错误和丑陋.谢谢.

Is there a more elegant way to reference all of R.id.buttonXXX ? It just looks so wrong and ugly. Thank you.

推荐答案

您的直觉是正确的.这很丑陋,总的来说,如果您发现自己想要这样做,您应该重新考虑您的设计.

Your instincts are correct. It's ugly and in general if you find yourself wanting to do this you should rethink your design.

如果您的按钮统一到您想要循环它们以执行此类操作的程度,则它们可能足够统一以首先以编程方式生成(并且您可以在创建它们时存储引用)或使用某种形式的 AdapterView.每个按钮需要关联哪些数据?可以直接使用 setTag/getTag 关联吗?这里需要用到ID吗?

If your buttons are uniform to the point where you want to loop over them to do something like this, they're probably uniform enough to generate programmatically in the first place (and you can store references as you create them) or use some form of AdapterView. What data needs to be associated with each button? Can you associate it directly using setTag/getTag? Do you need to use IDs here at all?

这篇关于android:如何优雅地设置多个按钮 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆