如何避免 Android 测试应用程序中的代码重复?
假设我有一个应用程序,其中有类似的按钮,名为“button0”、“button1”等,一直到“button9”。
如何在不重复代码的情况下执行以下操作?
button0 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button0);
button1 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button1);
...
button9 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button9);
我尝试使用反射,但代码看起来不干净。
for (int i = 0; i <= 9; i++) {
String btnName = "button" + i;
/* do reflection stuff to link self.buttonX
with a reference to com.sample.SampleApp.R.id.buttonX */
}
Suppose I have an application that have similar buttons named button0, button1, etc, up to button9.
How can I do the following without duplicating code?
button0 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button0);
button1 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button1);
...
button9 = (Button) activity.findViewById(com.sample.SampleApp.R.id.button9);
I tried to use reflection but the code looks unclean.
for (int i = 0; i <= 9; i++) {
String btnName = "button" + i;
/* do reflection stuff to link self.buttonX
with a reference to com.sample.SampleApp.R.id.buttonX */
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下代码未经测试,但请尝试一下:
使用 ArrayList (再次未经测试 - 只是为了让您了解我的意思):
The following code is untested, but give it a try:
With ArrayList (again untested - just to give you an idea of what I mean):