如果您创建了一个SurfaceView
包含 x 和 y 变量的子类,则最佳做法是为这些变量创建 setter 和 getter(我将其称为setPositionX()
而不是setX()
,因为SurfaceView
已经有了该方法):
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;
}
}
在您的活动中:
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();
}