java - Cannot refer to the non-final local variable button defined in an enclosing scope, Random method error -
i getting error in project eclipse:
cannot refer non-final local variable button defined in enclosing scope
this class:
import android.app.activity; import android.content.context; import android.graphics.point; import android.os.bundle; import android.support.annotation.nonnull; import android.widget.button; import android.view.menu; import android.view.menuitem; import android.view.windowmanager; import java.util.random; import java.util.timer; import java.util.timertask; public class mainactivity extends activity { button buttonblack; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); buttonblack = (button)findviewbyid(r.id.button01); startrandombutton(buttonblack); } public static point getdisplaysize(@nonnull context context) { point point = new point(); windowmanager manager = (windowmanager) context.getsystemservice(context.window_service); manager.getdefaultdisplay().getsize(point); return point; } private void setbuttonrandomposition(button button){ int randomx = new random().nextint(getdisplaysize(this).x); int randomy = new random().nextint(getdisplaysize(this).y); button.setx(randomx); button.sety(randomy); } private void startrandombutton(button button) { timer timer = new timer(); timer.schedule(new timertask() { @override public void run() { setbuttonrandomposition(button); } }, 0, 1000);//update button every second } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); if (id == r.id.action_settings) { return true; } return super.onoptionsitemselected(item); } }
the problem in method:
private void startrandombutton(button button) { timer timer = new timer(); timer.schedule(new timertask() { @override public void run() { setbuttonrandomposition(button);// cannot refer non-final local variable button defined in enclosing scope } }, 0, 1000);//update button every second }
can me fix this? or suggest other code better this?
you have declared button buttonblack;
globally in mainactivity
..
you can pass buttonblack
setbuttonrandomposition(buttonblack);
without referring final
.
Comments
Post a Comment