I’ve been having problems with Android buttons. I try to set an onClick listener, but it fails, crashes and doesn’t print any helpeul error messages. Here is my code:
Button button;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.choose_level);
}
});
I’ve tried putting in a try catch statement so it won’t display annoying errors but the button still doesn’t work. Would it be because the layout hasn’t been loaded? or is it something else?
Thanks in advance.
you must call
setContentView(R.layout.XML_LAYOUT);method before you callfindViewByIdfor your button.here XML_LAYOUT must be the Layout containing your Button ID.
Note:- it is not recommanded to call setContentView method multiple times. if you want to show a different layout/screen add it into Another activity and start that activity on button click.