Skip to content Skip to sidebar Skip to footer

Why Does Onclicklistener Not Work Outside Of Oncreate Method?

When I try to use the onClickListener method for a button, variable outside of any onCreate or onPause or onAnything method, it does not work. I also cannot even set the value of a

Solution 1:

One thing I notice about your code is that you are initializing your views when you declare them, which is before you set the content view. Find view by id will not work until after you do so. Change it so you declare them like

Button add;
Button sub;

...
    setContentView(R.layout.main);
    add = (Button) findViewById(R.id.bAdd);
    sub = (Button) findViewById(R.id.bSub);

Also, the error message you are seeing is because you cannot execute that statement outside of a method. You should be doing it inside onCreate anyway.

Solution 2:

You should go thorugh this blog - Different Ways To Handle Clicks

Post a Comment for "Why Does Onclicklistener Not Work Outside Of Oncreate Method?"