如何避免 Android 测试应用程序中的代码重复?

发布于 2024-12-07 05:23:41 字数 589 浏览 1 评论 0原文

假设我有一个应用程序,其中有类似的按钮,名为“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮邮递员 2024-12-14 05:23:41

以下代码未经测试,但请尝试一下:

Button[] buttons = new Button[]{button0, button1, button2, button3, button4, button5, button6, button7, button8, button9};
for (int i = 0; i < buttons.length, i++) {
   buttons[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}

使用 ArrayList (再次未经测试 - 只是为了让您了解我的意思):

ArrayList<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < 10, i++) {
   buttons.add(new Button(this));
   buttons.get(i) = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}

The following code is untested, but give it a try:

Button[] buttons = new Button[]{button0, button1, button2, button3, button4, button5, button6, button7, button8, button9};
for (int i = 0; i < buttons.length, i++) {
   buttons[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}

With ArrayList (again untested - just to give you an idea of what I mean):

ArrayList<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < 10, i++) {
   buttons.add(new Button(this));
   buttons.get(i) = (Button) findViewById(getResources().getIdentifier("button" + i, "id", "com.sample.SampleApp"));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文