Reputation: 665
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.
Upvotes: 0
Views: 112
Reputation:
you are calling setContentView(R.Layout.XML_LAYOUT) in your button onClick listener where as it should be above in oncreate method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
show ur text here
}
});
I guess what u r trying to do is to set view for an XML file which is some layout file i guess check out inflator and intent
Upvotes: 1
Reputation: 27549
you must call setContentView(R.layout.XML_LAYOUT);
method before you callfindViewById
for 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.
Upvotes: 1
Reputation: 103837
I put that in a try, catch statement so it won't put annoying errors...
A catch
block will not magically stop your error from occurring - you cannot use it to stop the application "putting annoying errors".
You use them to handle errors when it's possible to recover from those cases (e.g. wait and retry, fall back to a slower alternative, etc.)
What is the implementation of your catch block? If you're simply swallowing the error, your app will still fail - only you won't have any diagnostic information with which to deal with it.
You'll need to go back to your original "annoying error", work out why it was happening and then fix it rather than just suppressing its output.
Upvotes: 0