简体   繁体   中英

When the button is pressed, the app crashes

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 call findViewById 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.

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 ur trying to do is to set view for an XML file which is some layout file i guess check out inflator and intent

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM