Question

I already have x and y variables on surfaceview but don't know how to accsess them from my main activity where my button stays.

This looks like a million dollar question no one answers me I've posted this question several times and I cant find anything related to this.

here is the button:

 Button1.setOnClickListener(this);
    }

    public void onClick(View v) {


//I want to access variable x and y of surfaceview


             if (x==230)
            x=x +20;

        invalidate();

    }

thanks in advance

Was it helpful?

Solution

If you've created a subclass of SurfaceView where you have your x and y variables, best practice would be to create setters and getters for those variables (I'm calling it setPositionX() instead of setX(), because SurfaceView already has that method):

public class MySurfaceView extends SurfaceView {
    private int x;

    private int y;

    public void setPositionX(int x) {
        this.x = x;
    }

    public void setPositionY(int y) {
        this.y = y;
    }

    public int getPositionX() {
        return x;
    }

    public int getPositionY() {
        return y;
    }
}

and in your Activity:

private MySurfaceView mySurfaceView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // Create SurfaceView and assign it to a variable.
    mySurfaceView = new MySurfaceView(this);

    // Do other initialization. Create button listener and other stuff.
    button1.setOnClickListener(this);
}

public void onClick(View v) {
    int x = mySurfaceView.getPositionX();
    int y = mySurfaceView.getPositionY();

    if (x == 230) {
        mySurfaceView.setPositionX(x + 20);
    }

    invalidate();
}

OTHER TIPS

Did you try using an interface? Once you get the x and y values you can pass them to an interface method. Then you can implement that interface on your MainActivity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top