简体   繁体   中英

“Cannot refer to a non-final variable buttonflag inside an inner class defined in a different method”

boolean buttonflag=false;
        Editbutton.setOnClickListener( new OnClickListener()
        { 


            @Override
            public void onClick( View v )
            {
               buttonflag=true;

             }
        }

error im getting is "Cannot refer to a non-final variable buttonflag inside an inner class defined in a different method" what i want to do is when i press the Editbutton i want the buttonflag to be true..Can any one explain the reason and a fix for this problem?

The error message is pretty straight forward. Since buttonflag is not final, you cannot access it in your OnClickListener anonymous class. Two possible solutions

  1. Make buttonflag a field
  2. Make it final. However, then you cannot modify it, and you have to choose the one-dimensional array approach resulting in

     final boolean[] buttonflag=new boolean[]{false}; Editbutton.setOnClickListener( new OnClickListener(){ @Override public void onClick( View v ){ buttonflag[0]=true; } } 

For this case, you will have to make it a field. The other @Robin correctly shows you two approaches to fix your problem, however since this is a call back mechanism which will get called multiple times (it is a callback on a button after all), the local variable is of little use since it will likely pass out of scope before the method is called.

Even though it won't fail, since the value being set is no longer accessible by any other part of your code it will serve little purpose. I would assume you are trying to set some state when the button is pushed, therefore that state needs to be stored as a field to be accessible when the method containing the shown code has ended.

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