Hi I’m new to android programming, I’m trying to initiate the on click method for all the buttons in my layout. I’ve wrote the following code :
public class SudokuActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setAllOnClick();
}
private void setAllOnClick(){
LayoutInflater li = getLayoutInflater();
LinearLayout ll = (LinearLayout) li.inflate(R.layout.main, null);
ArrayList<View> touchables = ll.getTouchables();
for (View v : touchables){
if (v instanceof Button){
Toast.makeText(getApplicationContext(), ((Button) v).getText() , Toast.LENGTH_SHORT).show();
v.setOnClickListener(this);
}
}
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), ((Button) v).getText() , Toast.LENGTH_SHORT).show();
}
}
The toast in the for works great – meaning I menage to get all the instances of my buttons,
but the toast in the onClick method doesn’t work, in fact I’ve seen in the debugger that it never reaches the onClick method, but I can’t figure out why ?
Thanks, and sorry if it’s too nooby, or if I haven’t noticed something very stupid!
Your problem is your inflating a new view and adding the click listeners to that, you want to add the listeners to the view on the screen.
Here this works: