0

我在主要活動中有兩個按鈕,不帶xml編程。 按鈕應該移動sur​​faceview上的位圖,我該如何實現這一點?如何從主要活動訪問變量到surfaceview Android?

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

    } 

回答

1

如果您已經創建了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

非常感謝 –

0

如果您希望將值傳遞迴原始活動,則應該使用startActivityForResult。

然後,您可以訪問它們在onActivityResult回調

+0

一些例子將不勝感激 –

相關問題