gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:46:34 25 4
gpt4 key购买 nike

假设我有一个应用程序具有类似的按钮,名称为 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 */
}

最佳答案

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

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"));
}

关于android - 如何避免 Android 测试应用程序中的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7588957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com