Android 如何使用mainactivity上的“我的按钮”控制画布位图?
我在surfaceview上已经有了x和y变量,但不知道如何从中访问它们 我的主要活动,我的按钮停留 这看起来像一个百万美元的问题没有人回答我,我已经贴了好几次这个问题,我找不到任何与此相关的东西 这是按钮:Android 如何使用mainactivity上的“我的按钮”控制画布位图?,android,android-canvas,surfaceview,android-button,bitmapfactory,Android,Android Canvas,Surfaceview,Android Button,Bitmapfactory,我在surfaceview上已经有了x和y变量,但不知道如何从中访问它们 我的主要活动,我的按钮停留 这看起来像一个百万美元的问题没有人回答我,我已经贴了好几次这个问题,我找不到任何与此相关的东西 这是按钮: Button1.setOnClickListener(this); } public void onClick(View v) { //I want to access variable x and y of surfaceview i
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();
}
提前感谢您尝试过使用界面吗?一旦获得x和y值,就可以将它们传递给接口方法。然后您可以在MainActivity上实现该接口。如果您已经创建了
SurfaceView
的子类,其中包含x和y变量,那么最好的做法是为这些变量创建setter和getter(我称之为setPositionX()
而不是setX()
,因为SurfaceView
已经有了该方法):
在你的活动中:
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();
}
我对这方面还不太熟悉一些例子也会很受欢迎,如果你把变量设置为公共的和静态的,那么它们就可以从任何地方访问。使用接口的好处是它充当侦听器。执行流将返回到调用类。在这里您可以找到如何定义接口。
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();
}