java - onClick method doesnt work -
protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_play); gl = (gridlayout) findviewbyid(r.id.grid); array = new button[7][6]; button btn; for(int i=0; i<7; i++) { for(int j=0; j<6; j++) { btn = new button(this); btn.setid(7*i + j + 1); array[i][j] = btn; gl.addview(btn); } } turn = 0; toast.maketext(this, "test", toast.length_short).show(); } @override public void onclick(view v) { toast.maketext(this, "test1", toast.length_short).show(); if(v instanceof button) { toast.maketext(this, "test2", toast.length_short).show(); int[] d = getcellbyid(v.getid()); button b = (button)v; b.setenabled(false); if(turn == 0) { b.setbackgroundcolor(color.yellow); turn = 1; } else { b.setbackgroundcolor(color.red); turn = 0; } array[d[0]][d[1]] = b; } }
this code, toasts testing if code running. activity implements onclicklistener
the onclick
method not work, used because have 42 buttons , can't write 42 setonclicklistener()
methods each button.
in code create, in 2 loop, 42 buttons (7*6) , every time each button pressed disabled , change background color of button 1 time yellow next time red , again.
you missing call following inside nested for
loop:
btn.setonclicklistener(this);
here, this
refers activity
implements onclicklistener
Comments
Post a Comment