Optimising Android/Java Code - Creating multiple instances of the same object type -
i have working application want optimise code. below 1 example create 10 separate imagebuttons (note incrementing objectname , xml reference each) , set listeners. can suggest more optimal way of doing this, perhaps in dynamic method/loop please? thanks....
private void initialisebuttons() { imagebutton imagebutton1 = (imagebutton)this.findviewbyid(r.id.imagebutton1); imagebutton1.setonclicklistener(this); imagebutton imagebutton2 = (imagebutton)this.findviewbyid(r.id.imagebutton2); imagebutton2.setonclicklistener(this); imagebutton imagebutton3 = (imagebutton)this.findviewbyid(r.id.imagebutton3); imagebutton3.setonclicklistener(this); imagebutton imagebutton4 = (imagebutton)this.findviewbyid(r.id.imagebutton4); imagebutton4.setonclicklistener(this); imagebutton imagebutton5 = (imagebutton)this.findviewbyid(r.id.imagebutton5); imagebutton5.setonclicklistener(this); imagebutton imagebutton6 = (imagebutton)this.findviewbyid(r.id.imagebutton6); imagebutton6.setonclicklistener(this); imagebutton imagebutton7 = (imagebutton)this.findviewbyid(r.id.imagebutton7); imagebutton7.setonclicklistener(this); imagebutton imagebutton8 = (imagebutton)this.findviewbyid(r.id.imagebutton8); imagebutton8.setonclicklistener(this); imagebutton imagebutton9 = (imagebutton)this.findviewbyid(r.id.imagebutton9); imagebutton9.setonclicklistener(this); imagebutton imagebutton0 = (imagebutton)this.findviewbyid(r.id.imagebutton0); imagebutton0.setonclicklistener(this); }
you can use arrays, lists ...
for example:
private static final int[] buttons_ids = new int[] {r.id.imagebutton0, r.id.imagebutton1, r.id.imagebutton2, r.id.imagebutton3, r.id.imagebutton4, r.id.imagebutton5, r.id.imagebutton6, r.id.imagebutton7, r.id.imagebutton8, r.id.imagebutton9}; imagebutton[] buttons = new imagebutton[button_ids.length]; private void initialisebuttons() { (int = 0; < buttons_ids.length; i++) { buttons[i] = (imagebutton) findviewbyid(buttons_ids[i]); buttons[i].setonclicklistener(this); } }
you can put list of ids in arrays.xml file.