简体   繁体   中英

calling an activity method from custom onClickListener class

i trying to call a method that stays in my MainActivity class from custom onClickListener object. And there is something wrong with variable scope.

so in my MainActivity i have:

Button resetButton = (Button) findViewById(R.id.ResetButton);
View.OnClickListener myListener = new MyListener(GameBoard, width);
resetButton.setOnClickListener(myListener);

this is what my myListener class look like:

public class MyListener implements View.OnClickListener
{
    private static MainActivity mainActivity;
    public MyListener(MainActivity mainActivity) {
    this.mainActivity = mainActivity;
}

    @Override
    public void onClick(View v) {
        mainActivity.myMethod();
    }
}

and method also in MainActivity that uses some MainActivity instance variables:

public void myMethod()
{
    InstanceVariable++;  // for example
}

Then when calling that myMethod on mainActivity object that i passing to myListener constructor by clicking resetButton i getting an error something about MainActivity InstanceVariable scope. I`m very beginner to android programming, so i cant fully understand where its coming from.

And this error disappears when i pass this InstanceVariable to constructor of myListener object . I think there should be an easier way to do that.

Change to:

public void myMethod() {
    mainActivity.instanceVariable++;  // for example
}

instancevariable is not visible in your MyListener class, you have to point that it ts in the mainActivity object.

If your instanceVariable is private, create getter function in mainActivity:

public void getInstanceVariable() {
   return this.instanceVariable
}

and use it this way:

public void myMethod() {
        mainActivity.setInstanceVariable(mainActivity.getInstanceVariable()+1);  // for example
    }

make InstanceVariable to

public static int InstanceVariable;

and use this

 @Override 
    public void onClick(View v) {
        MainActivity.InstanceVariable++;
    } 

don't make methods for function that has less than 8 lines

Try this :

Make your listener an inner class of your activity, then :

class MyListener implements View.OnClickListener {

public MyListener() {

         }

@Override
public void onClick(View v) {
    MainActivity.this.myMethod();
}

}

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