Is there a fast way to initialize multiple buttons numbered 1-10 using for loop? (Android Application) -


i have init method finds each button using findviewbyid(r.id.pin1) , sets onclick method has method write bluetooth output stream.

    button mybutton = (button) findviewbyid(r.id.pin1);     mybutton.setonclicklistener(new onclicklistener() {          @override         public void onclick(view v) {             // todo auto-generated method stub             string msg = "1".tostring();             try {                 mmoutstream.write(msg.getbytes());             } catch (ioexception e) {                 error();             }         }     }); 

very quite literally, change 1 2 , on. next code segment is:

    button mybutton = (button) findviewbyid(r.id.pin2);     mybutton.setonclicklistener(new onclicklistener() {          @override         public void onclick(view v) {             // todo auto-generated method stub             string msg = "2".tostring();             try {                 mmoutstream.write(msg.getbytes());             } catch (ioexception e) {                 error();             }         }     }); 

i tried few things making string string pinbutton = "pin" + i.tostring() , r.id.pinbutton doesn't work. (that is, in forloop surrounded code with)

yes, can switch on button id , call same onclick() each button in xml change msg variable depending on id clicked

@override     public void myclick(view v) {       string msg = "";        switch (v.getid())        {              case (r.id.button1):               msg = "1";               break;               case (r.id.button2):               msg = "2";              break       }         try {             mmoutstream.write(msg.getbytes());         } catch (ioexception e) {             error();         }     } }); 

to set onclick() in xml each button

<button     ...     android:onclick="myclick"/> // name whatever want method called , same each button 

also, don't need call tostring() on msg since string


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -