2011-09-28 53 views
1

假设我有一个应用程序,名称为button0,button1等类似的按钮,直到button9。如何避免Android测试应用程序中的代码重复?

如何在不重复代码的情况下执行以下操作?

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

回答

1

下面的代码是未经测试,但不妨一试:

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

谢谢! getResources()。getIdentifier()会帮助很多,但有没有办法避免Button数组? – hgf

+0

我想你可以通过使用带Button元素的ArrayList来清理它,但我认为你不会比它更“干净”。我很想被证明是错的,虽然:) –

+0

ArrayList根本没有帮助,但你帮我看到,我不需要实例变量来引用UI元素,如果我可以创建一个局部变量来引用被测试的UI由findViewById发现的元素。谢谢。 – hgf