0

我已经在surfaceview上有x和y变量,但不知道如何从 那里获取我的按钮所在的主要活动。如何用主按钮上的按钮控制画布位图?

这看起来像一个百万美元的问题没有人回答我我发布了这个问题几次,我无法找到任何与此相关的任何东西。

这里的按钮:

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

    } 

在此先感谢

回答

0

如果您已经创建了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(); 
} 
0

你尝试使用的界面?一旦获得了x和y值,就可以将它们传递给接口方法。然后你可以在你的MainActivity上实现这个接口。

+0

我是新来的这个东东一些例子也将是赞赏 –

+0

,如果你把这些变量可能会更容易公共和静态的,所以他们可以从任何地方访问。使用接口的好处是它充当一个监听器。执行流程将返回到调用类。在这里你可以找到如何定义一个接口。 http://www.tutorialspoint.com/java/java_interfaces.htm – Emmanuel