如果您已经创建了SurfaceView
,你有你的变量x和y的子类,最好的做法是创建getter和setter方法为这些变量(我叫它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();
}
我是新来的这个东东一些例子也将是赞赏 –
,如果你把这些变量可能会更容易公共和静态的,所以他们可以从任何地方访问。使用接口的好处是它充当一个监听器。执行流程将返回到调用类。在这里你可以找到如何定义一个接口。 http://www.tutorialspoint.com/java/java_interfaces.htm – Emmanuel