Domanda

I have two buttons in main activity made programmatically without xml. The buttons should move the bitmap on the surfaceview, how can I achieve that?

here is one of the Buttons:

    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();

    }
È stato utile?

Soluzione

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();
}

Altri suggerimenti

You should use startActivityForResult if you want values to be passed back to the original activity.

You can then access them in onActivityResult callback

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top