开发者

How to avoid code duplication in a Android Test Application?

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 */
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜