我有一些共享相同的根綁定,有沒有辦法縮短代碼與一個while循環遍歷所有這些?優化java任務
RadioGroup G1, G2.. ... ...; // At class scope
TextView result1... .. ..;
/** ... */
public void bindViews() {
G1 = (RadioGroup) findViewById(R.id.radioGroup1);
G2 = (RadioGroup) findViewById(R.id.radioGroup2);
G3 = (RadioGroup) findViewById(R.id.radioGroup3);
G4 = (RadioGroup) findViewById(R.id.radioGroup4);
G5 = (RadioGroup) findViewById(R.id.radioGroup5);
G6 = (RadioGroup) findViewById(R.id.radioGroup6);
G7 = (RadioGroup) findViewById(R.id.radioGroup7);
G8 = (RadioGroup) findViewById(R.id.radioGroup8);
G9 = (RadioGroup) findViewById(R.id.radioGroup9);
G10 = (RadioGroup) findViewById(R.id.radioGroup10);
G11 = (RadioGroup) findViewById(R.id.radioGroup11);
G12 = (RadioGroup) findViewById(R.id.radioGroup12);
G13 = (RadioGroup) findViewById(R.id.radioGroup13);
G14 = (RadioGroup) findViewById(R.id.radioGroup14);
G15 = (RadioGroup) findViewById(R.id.radioGroup15);
G16 = (RadioGroup) findViewById(R.id.radioGroup16);
G17 = (RadioGroup) findViewById(R.id.radioGroup17);
G18 = (RadioGroup) findViewById(R.id.radioGroup18);
G19 = (RadioGroup) findViewById(R.id.radioGroup19);
G20 = (RadioGroup) findViewById(R.id.radioGroup20);
....
}
是否可以使用反射來減少冗餘代碼? 我的興趣主要是讓它更容易綁定> 40RadioGroups和TextViews。
我覺得一個for循環會更適合這裏,其實。 – RamenChef
在這種情況下,您可以使用增量索引的循環原因執行此操作,但是如果您想要一些常規操作,則故事是不同的! –
可能重複的[Android,從字符串獲取資源ID?](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string) –